johnmahugu

php - how to do a post request

Jun 14th, 2015
317
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.62 KB | None | 0 0
  1.  
  2. // How to do a POST request
  3.  
  4. // This example shows how to do a simple POST request to another webserver by using a socket connection.
  5.  
  6. function post_request($url, $data, $referer='') {
  7.  
  8.     // Convert the data array into URL Parameters like a=b&foo=bar etc.
  9.     $data = http_build_query($data);
  10.  
  11.     // parse the given URL
  12.     $url = parse_url($url);
  13.  
  14.     if ($url['scheme'] != 'http') {
  15.         die('Error: Only HTTP request are supported !');
  16.     }
  17.  
  18.     // extract host and path:
  19.     $host = $url['host'];
  20.     $path = $url['path'];
  21.  
  22.     // open a socket connection on port 80 - timeout: 30 sec
  23.     $fp = fsockopen($host, 80, $errno, $errstr, 30);
  24.  
  25.     if ($fp){
  26.  
  27.         // send the request headers:
  28.         fputs($fp, "POST $path HTTP/1.1\r\n");
  29.         fputs($fp, "Host: $host\r\n");
  30.  
  31.         if ($referer != '')
  32.             fputs($fp, "Referer: $referer\r\n");
  33.  
  34.         fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
  35.         fputs($fp, "Content-length: ". strlen($data) ."\r\n");
  36.         fputs($fp, "Connection: close\r\n\r\n");
  37.         fputs($fp, $data);
  38.  
  39.         $result = '';
  40.         while(!feof($fp)) {
  41.             // receive the results of the request
  42.             $result .= fgets($fp, 128);
  43.         }
  44.     }
  45.     else {
  46.         return array(
  47.             'status' => 'err',
  48.             'error' => "$errstr ($errno)"
  49.         );
  50.     }
  51.  
  52.     // close the socket connection:
  53.     fclose($fp);
  54.  
  55.     // split the result header from the content
  56.     $result = explode("\r\n\r\n", $result, 2);
  57.  
  58.     $header = isset($result[0]) ? $result[0] : '';
  59.     $content =
Advertisement
Add Comment
Please, Sign In to add comment