PHP发送POST请求的三种方式

来源:互联网 发布:手机淘宝的服务平台 编辑:程序博客网 时间:2024/05/18 21:05
[php] view plain copy
  1. <?php   
  2. //PHP发送POST请求的三种方式 分别使用curl  file_get_content  fsocket 来实现post提交数据  
  3. class Request{  
  4.     public static function post($url$post_data = ''$timeout = 5){//curl  
  5.         $ch = curl_init();  
  6.         curl_setopt ($ch, CURLOPT_URL, $url);  
  7.         curl_setopt ($ch, CURLOPT_POST, 1);  
  8.         if($post_data != ''){  
  9.             curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);  
  10.         }  
  11.         curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);   
  12.         curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);  
  13.         curl_setopt($ch, CURLOPT_HEADER, false);  
  14.         $file_contents = curl_exec($ch);  
  15.         curl_close($ch);  
  16.         return $file_contents;  
  17.     }  
  18.    
  19.     public static function post2($url$data){//file_get_content  
  20.         $postdata = http_build_query($data);  
  21.         $opts = array('http' =>   
  22.             array'method'  => 'POST','header'  => 'Content-type: application/x-www-form-urlencoded''content' => $postdata ) );  
  23.         $context = stream_context_create($opts);  
  24.         $result = file_get_contents($url, false, $context);  
  25.         return $result;  
  26.     }  
  27.    
  28.     public static function post3($host,$path,$query,$others=''){//fsocket  
  29.         $post="POST $path HTTP/1.1\r\nHost: $host\r\n";  
  30.         $post.="Content-type: application/x-www-form-";  
  31.         $post.="urlencoded\r\n${others}";  
  32.         $post.="User-Agent: Mozilla 4.0\r\nContent-length: ";  
  33.         $post.=strlen($query)."\r\nConnection: close\r\n\r\n$query";  
  34.         $h=fsockopen($host,80);  
  35.         fwrite($h,$post);  
  36.         for($a=0,$r='';!$a;){  
  37.             $b=fread($h,8192);  
  38.             $r.=$b;  
  39.             $a=(($b=='')?1:0);  
  40.         }  
  41.         fclose($h);  
  42.         return $r;  
  43.     }  
  44. }  
  45. ?>  
转自http://blog.csdn.net/muzi187/article/details/53305681
原创粉丝点击