php socket模拟http中post或get提交数据

php socket模拟http中post或者get提交数据的示例代码。
代码: 
sock_post.php: 
Java代码  收藏代码
  1. <?php  
  2. /** 
  3. * php socket模拟postget请求 
  4. * 编辑:脚本学堂 http://www.jbxue.com 
  5. */  
  6. function sock_post($url, $data='') {  
  7.   $url = parse_url($url);  
  8.   $url['scheme'] || $url['scheme'] = 'http';  
  9.   $url['host'] || $url['host'] = $_SERVER['HTTP_HOST'];  
  10.   $url['path'][0] != '/' && $url['path'] = '/'.$url['path'];  
  11.   
  12.   $query = $data;  
  13.   if(is_array($data)) $query = http_build_query($data);  
  14.   
  15.   $fp = @fsockopen($url['host'], $url['port'] ? $url['port'] : 80);  
  16.   if (!$fp) return "Failed to open socket to $url[host]";  
  17.   
  18.   fputs($fp, sprintf("POST %s%s%s HTTP/1.0/n", $url['path'], $url['query'] ? "?" : "", $url['query']));  
  19.   fputs($fp, "Host: $url[host]/n");  
  20.   fputs($fp, "Content-type: application/x-www-form-urlencoded/n");  
  21.   fputs($fp, "Content-length: " . strlen($query) . "/n");  
  22.   fputs($fp, "Connection: close/n/n");  
  23.   
  24.   fputs($fp, "$query/n");  
  25.   
  26.   $line = fgets($fp,1024);  
  27.   
  28.   if (@!eregi("^HTTP/1/.. 200", $line))  return;  
  29.   
  30.   $results = "";  
  31.   $inheader = 1;  
  32.   while(!feof($fp)) {  
  33.     $line = fgets($fp,1024);  
  34.     if ($inheader && ($line == "/n" || $line == "/r/n")) {  
  35.       $inheader = 0;  
  36.     }elseif (!$inheader) {  
  37.       $results .= $line;  
  38.     }  
  39.   }  
  40.   fclose($fp);  
  41.   
  42.   return $results;  
  43. }  
  44.  $re = sock_post('http://localhost/direct_post/get_post.php?id=1',array('wel'=>'hello'));  
  45.  echo $re;  
  46. ?>  


get_post.php: 
Java代码  收藏代码
  1. <?php  
  2. echo "post:";  
  3. print_r($_POST);  
  4. echo 'get:';  
  5. print_r($_GET);  
  6. ?>  
 
原文地址:https://www.cnblogs.com/hasayaki/p/3410093.html