Created
February 11, 2013 08:36
-
-
Save apphp-snippets/4753272 to your computer and use it in GitHub Desktop.
Doing POST Request by Socket Connection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // source: http://www.apphp.com/index.php?snippet=php-post-request-by-socket-connection | |
| // submit these variables to the server | |
| $post_data = array("test"=>"yes", "passed"=>"yes", "id"=>"3"); | |
| // send a request to specified server | |
| $result = do_post_request("http://www.example.com/", $post_data); | |
| if($result["status"] == "ok"){ | |
| // headers | |
| echo $result["header"]; | |
| // result of the request | |
| echo $result["content"]; | |
| }else{ | |
| echo "An error occurred: ".$result["error"]; | |
| } | |
| function do_post_request($url, $data, $referer = ""){ | |
| // convert the data array into URL Parameters like a=1&b=2 etc. | |
| $data = http_build_query($data); | |
| // parse the given URL | |
| $url = parse_url($url); | |
| if($url["scheme"] != "http"){ | |
| die("Error: only HTTP requests supported!"); | |
| } | |
| // extract host and path from url | |
| $host = $url["host"]; | |
| $path = $url["path"]; | |
| // open a socket connection with port 80, set timeout 40 sec. | |
| $fp = fsockopen($host, 80, $errno, $errstr, 40); | |
| $result = ""; | |
| if($fp){ | |
| // send a request headers | |
| fputs($fp, "POST $path HTTP/1.1\r\n"); | |
| fputs($fp, "Host: $host\r\n"); | |
| if($referer != "") fputs($fp, "Referer: $referer\r\n"); | |
| fputs($fp, "Content-type: application/x-www-form-urlencode | |
| d\r\n"); | |
| fputs($fp, "Content-length: ".strlen($data)."\r\n"); | |
| fputs($fp, "Connection: close\r\n\r\n"); | |
| fputs($fp, $data); | |
| // receive result from request | |
| while(!feof($fp)) $result .= fgets($fp, 128); | |
| }else{ | |
| return array("status"=>"err", "error"=>"$errstr ($errno)"); | |
| } | |
| // close socket connection | |
| fclose($fp); | |
| // split result header from the content | |
| $result = explode("\r\n\r\n", $result, 2); | |
| $header = isset($result[0]) ? $result[0] : ""; | |
| $content = isset($result[1]) ? $result[1] : ""; | |
| // return as structured array: | |
| return array( | |
| "status" => "ok", | |
| "header" => $header, | |
| "content" => $content | |
| ); | |
| } | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment