Posted By

apphp-snippets on 02/13/13


Tagged

php post socket request


Versions (?)

Doing POST Request by Socket Connection


 / Published in: PHP
 

URL: http://www.apphp.com/index.php?snippet=php-post-request-by-socket-connection

This example of code shows how to do a simple POST request in PHP to another web server by using a socket connection.

  1. <?php
  2. // submit these variables to the server
  3. $post_data = array("test"=>"yes", "passed"=>"yes", "id"=>"3");
  4.  
  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.  
  16. function do_post_request($url, $data, $referer = ""){
  17. // convert the data array into URL Parameters like a=1&b=2 etc.
  18. $data = http_build_query($data);
  19. // parse the given URL
  20. $url = parse_url($url);
  21.  
  22. if($url["scheme"] != "http"){
  23. die("Error: only HTTP requests supported!");
  24. }
  25.  
  26. // extract host and path from url
  27. $host = $url["host"];
  28. $path = $url["path"];
  29.  
  30. // open a socket connection with port 80, set timeout 40 sec.
  31. $fp = fsockopen($host, 80, $errno, $errstr, 40);
  32. $result = "";
  33.  
  34. if($fp){
  35. // send a request headers
  36. fputs($fp, "POST $path HTTP/1.1
  37. ");
  38. fputs($fp, "Host: $host
  39. ");
  40. if($referer != "") fputs($fp, "Referer: $referer
  41. ");
  42. fputs($fp, "Content-type: application/x-www-form-urlencode
  43. d
  44. ");
  45. fputs($fp, "Content-length: ".strlen($data)."
  46. ");
  47. fputs($fp, "Connection: close
  48.  
  49. ");
  50. fputs($fp, $data);
  51.  
  52. // receive result from request
  53. while(!feof($fp)) $result .= fgets($fp, 128);
  54. }else{
  55. return array("status"=>"err", "error"=>"$errstr ($errno)");
  56. }
  57.  
  58. // close socket connection
  59. fclose($fp);
  60.  
  61. // split result header from the content
  62. $result = explode("
  63.  
  64. ", $result, 2);
  65.  
  66. $header = isset($result[0]) ? $result[0] : "";
  67. $content = isset($result[1]) ? $result[1] : "";
  68.  
  69. // return as structured array:
  70. return array(
  71. "status" => "ok",
  72. "header" => $header,
  73. "content" => $content
  74. );
  75. }
  76.  
  77. ?>

Report this snippet  

You need to login to post a comment.