Doing POST Request By Socket Connection


SUBMITTED BY: Guest

DATE: June 12, 2013, 1:24 a.m.

FORMAT: PHP

SIZE: 2.4 kB

HITS: 1229

  1. <?php
  2. // source: http://www.apphp.com/index.php?snippet=php-post-request-by-socket-connection
  3. // submit these variables to the server
  4. $post_data = array("test"=>"yes", "passed"=>"yes", "id"=>"3");
  5. // send a request to specified server
  6. $result = do_post_request("http://www.example.com/", $post_data);
  7. if($result["status"] == "ok"){
  8. // headers
  9. echo $result["header"];
  10. // result of the request
  11. echo $result["content"];
  12. }else{
  13. echo "An error occurred: ".$result["error"];
  14. }
  15. function do_post_request($url, $data, $referer = ""){
  16. // convert the data array into URL Parameters like a=1&b=2 etc.
  17. $data = http_build_query($data);
  18. // parse the given URL
  19. $url = parse_url($url);
  20. if($url["scheme"] != "http"){
  21. die("Error: only HTTP requests supported!");
  22. }
  23. // extract host and path from url
  24. $host = $url["host"];
  25. $path = $url["path"];
  26. // open a socket connection with port 80, set timeout 40 sec.
  27. $fp = fsockopen($host, 80, $errno, $errstr, 40);
  28. $result = "";
  29. if($fp){
  30. // send a request headers
  31. fputs($fp, "POST $path HTTP/1.1\r\n");
  32. fputs($fp, "Host: $host\r\n");
  33. if($referer != "") fputs($fp, "Referer: $referer\r\n");
  34. fputs($fp, "Content-type: application/x-www-form-urlencode
  35. d\r\n");
  36. fputs($fp, "Content-length: ".strlen($data)."\r\n");
  37. fputs($fp, "Connection: close\r\n\r\n");
  38. fputs($fp, $data);
  39. // receive result from request
  40. while(!feof($fp)) $result .= fgets($fp, 128);
  41. }else{
  42. return array("status"=>"err", "error"=>"$errstr ($errno)");
  43. }
  44. // close socket connection
  45. fclose($fp);
  46. // split result header from the content
  47. $result = explode("\r\n\r\n", $result, 2);
  48. $header = isset($result[0]) ? $result[0] : "";
  49. $content = isset($result[1]) ? $result[1] : "";
  50. // return as structured array:
  51. return array(
  52. "status" => "ok",
  53. "header" => $header,
  54. "content" => $content
  55. );
  56. }
  57. ?>

comments powered by Disqus