当前位置:首页 > PHP教程 > php高级应用 > 列表

php使用socket post数据到其它web服务器的方法

发布:smiling 来源: PHP粉丝网  添加日期:2021-05-27 14:32:29 浏览: 评论:0 

这篇文章主要介绍了php使用socket post数据到其它web服务器的方法,涉及php使用socket传输数据的相关技巧,需要的朋友可以参考下。

本文实例讲述了php使用socket post数据到其它web服务器的方法,分享给大家供大家参考,具体实现方法如下:

  1. function post_request($url, $data, $referer='') { 
  2.   // Convert the data array into URL Parameters like a=b&foo=bar etc. 
  3.   $data = http_build_query($data); 
  4.   // parse the given URL 
  5.   $url = parse_url($url); 
  6.   if ($url['scheme'] != 'http') {  
  7.     die('Error: Only HTTP request are supported !'); 
  8.   } 
  9.   // extract host and path: 
  10.   $host = $url['host']; 
  11.   $path = $url['path']; 
  12.   // open a socket connection on port 80 - timeout: 30 sec 
  13.   $fp = fsockopen($host, 80, $errno, $errstr, 30); 
  14.   if ($fp){ 
  15.     // send the request headers: 
  16.     fputs($fp, "POST $path HTTP/1.1\r\n"); 
  17.     fputs($fp, "Host: $host\r\n"); 
  18.     if ($referer != '') 
  19.       fputs($fp, "Referer: $referer\r\n"); 
  20.     fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n"); 
  21.     fputs($fp, "Content-length: ". strlen($data) ."\r\n"); 
  22.     fputs($fp, "Connection: close\r\n\r\n"); 
  23.     fputs($fp, $data); 
  24.     $result = '';  
  25.     while(!feof($fp)) { 
  26.       // receive the results of the request 
  27.       $result .= fgets($fp, 128); 
  28.     } 
  29.   } 
  30.   else {  
  31.     return array( 
  32.       'status' => 'err',  
  33.       'error' => "$errstr ($errno)" 
  34.     ); 
  35.   } 
  36.   // close the socket connection: 
  37.   fclose($fp); 
  38.   // split the result header from the content 
  39.   $result = explode("\r\n\r\n", $result, 2); 
  40.   $header = isset($result[0]) ? $result[0] : ''; 
  41.   $content = isset($result[1]) ? $result[1] : ''; 
  42.   // return as structured array: 
  43.   return array( 
  44.     'status' => 'ok', 
  45.     'header' => $header, 
  46.     'content' => $content 
  47.   ); 
  48. } 
  49. //使用方法 
  50. // Submit those variables to the server 
  51. $post_data = array( 
  52.   'test' => 'foobar', 
  53.   'okay' => 'yes', 
  54.   'number' => 2 
  55. ); 
  56. // Send a request to example.com  
  57. $result = post_request('http://www.phpfensi.com/', $post_data); 
  58. if ($result['status'] == 'ok'){ 
  59.   // Print headers  
  60.   echo $result['header'];  
  61.   echo '<hr />'; 
  62.   // print the result of the whole request: 
  63.   echo $result['content']; 
  64. } 
  65. else { 
  66.   echo 'A error occured: ' . $result['error'];  
  67. }

Tags: socket web服务器

分享到: