[PHP] Effettuare richieste POST con le connessioni socket

Nel tutorial PHP di oggi vi mostreremo come effettuare richieste POST su un altro web server con le connessioni socket.

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