Posted By

apphp-snippets on 02/27/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\r\n");
  37. fputs($fp, "Host: $host\r\n");
  38. if($referer != "") fputs($fp, "Referer: $referer\r\n");
  39. fputs($fp, "Content-type: application/x-www-form-urlencode
  40. d\r\n");
  41. fputs($fp, "Content-length: ".strlen($data)."\r\n");
  42. fputs($fp, "Connection: close\r\n\r\n");
  43. fputs($fp, $data);
  44.  
  45. // receive result from request
  46. while(!feof($fp)) $result .= fgets($fp, 128);
  47. }else{
  48. return array("status"=>"err", "error"=>"$errstr ($errno)");
  49. }
  50.  
  51. // close socket connection
  52. fclose($fp);
  53.  
  54. // split result header from the content
  55. $result = explode("\r\n\r\n", $result, 2);
  56.  
  57. $header = isset($result[0]) ? $result[0] : "";
  58. $content = isset($result[1]) ? $result[1] : "";
  59.  
  60. // return as structured array:
  61. return array(
  62. "status" => "ok",
  63. "header" => $header,
  64. "content" => $content
  65. );
  66. }
  67.  
  68. ?>

Report this snippet  

You need to login to post a comment.