PHP发送POST请求

来源:互联网 发布:房价会如何变化 知乎 编辑:程序博客网 时间:2024/05/17 09:20


  1. /** 
  2.  * 发送post请求 
  3.  * @param string $url 请求地址 
  4.  * @param array $post_data post键值对数据 
  5.  * @return string 
  6.  */  
  7. function send_post($url$post_data) {  
  8.   
  9.   $postdata = http_build_query($post_data);  
  10.   $options = array(  
  11.     'http' => array(  
  12.       'method' => 'POST',  
  13.       'header' => 'Content-type:application/x-www-form-urlencoded',  
  14.       'content' => $postdata,  
  15.       'timeout' => 15 * 60 // 超时时间(单位:s)  
  16.     )  
  17.   );  
  18.   $context = stream_context_create($options);  
  19.   $result = file_get_contents($url, false, $context);  
  20.   
  21.   return $result;  
  22. }  
  23.   
  24. //使用方法  
  25. $post_data = array(  
  26.   'username' => 'stclair2201',  
  27.   'password' => 'handan'  
  28. );  
  29. send_post('http://www.qianyunlai.com'$post_data);  
  30.   
  31.   
  32.   
  33.   
  34. <?php  
  35. /** 
  36.  * Socket版本 
  37.  * 使用方法: 
  38.  * $post_string = "app=socket&version=beta"; 
  39.  * request_by_socket('chajia8.com', '/restServer.php', $post_string); 
  40.  */  
  41. function request_by_socket($remote_server,$remote_path,$post_string,$port = 80,$timeout = 30) {  
  42.   $socket = fsockopen($remote_server$port$errno$errstr$timeout);  
  43.   if (!$socketdie("$errstr($errno)");  
  44.   fwrite($socket"POST $remote_path HTTP/1.0");  
  45.   fwrite($socket"User-Agent: Socket Example");  
  46.   fwrite($socket"HOST: $remote_server");  
  47.   fwrite($socket"Content-type: application/x-www-form-urlencoded");  
  48.   fwrite($socket"Content-length: " . (strlen($post_string) + 8) . "");  
  49.   fwrite($socket"Accept:*/*");  
  50.   fwrite($socket"");  
  51.   fwrite($socket"mypost=$post_string");  
  52.   fwrite($socket"");  
  53.   $header = "";  
  54.   while ($str = trim(fgets($socket, 4096))) {  
  55.     $header .= $str;  
  56.   }  
  57.   
  58.   $data = "";  
  59.   while (!feof($socket)) {  
  60.     $data .= fgets($socket, 4096);  
  61.   }  
  62.   
  63.   return $data;  
  64. }  
  65. ?>  
  66.   
  67. <?php  
  68. /**  
  69.  * Curl版本  
  70.  * 使用方法:  
  71.  * $post_string = "app=request&version=beta";  
  72.  * request_by_curl('http://www.qianyunlai.com/restServer.php'$post_string);  
  73.  */  
  74. function request_by_curl($remote_server$post_string) {  
  75.   $ch = curl_init();  
  76.   curl_setopt($ch, CURLOPT_URL, $remote_server);  
  77.   curl_setopt($ch, CURLOPT_POSTFIELDS, 'mypost=' . $post_string);  
  78.   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
  79.   curl_setopt($ch, CURLOPT_USERAGENT, "qianyunlai.com's CURL Example beta");  
  80.   $data = curl_exec($ch);  
  81.   curl_close($ch);  
  82.   
  83.   return $data;  
  84. }  
  85. ?>  
原文地址:http://blog.sjzycxx.cn/post/435/
0 0
原创粉丝点击