PHP发送POST请求的三种方式

原创
2016-07-25 08:41:53 675浏览
[PHP]代码
  1. class Request{
  2. public static function post($url, $post_data = '', $timeout = 5){//curl
  3. $ch = curl_init();
  4. curl_setopt ($ch, CURLOPT_URL, $url);
  5. curl_setopt ($ch, CURLOPT_POST, 1);
  6. if($post_data != ''){
  7. curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
  8. }
  9. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  10. curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  11. curl_setopt($ch, CURLOPT_HEADER, false);
  12. $file_contents = curl_exec($ch);
  13. curl_close($ch);
  14. return $file_contents;
  15. }
  16. public static function post2($url, $data){//file_get_content
  17. $postdata = http_build_query(
  18. $data
  19. );
  20. $opts = array('http' =>
  21. array(
  22. 'method' => 'POST',
  23. 'header' => 'Content-type: application/x-www-form-urlencoded',
  24. 'content' => $postdata
  25. )
  26. );
  27. $context = stream_context_create($opts);
  28. $result = file_get_contents($url, false, $context);
  29. return $result;
  30. }
  31. public static function post3($host,$path,$query,$others=''){//fsocket
  32. $post="POST $path HTTP/1.1\r\nHost: $host\r\n";
  33. $post.="Content-type: application/x-www-form-";
  34. $post.="urlencoded\r\n${others}";
  35. $post.="User-Agent: Mozilla 4.0\r\nContent-length: ";
  36. $post.=strlen($query)."\r\nConnection: close\r\n\r\n$query";
  37. $h=fsockopen($host,80);
  38. fwrite($h,$post);
  39. for($a=0,$r='';!$a;){
  40. $b=fread($h,8192);
  41. $r.=$b;
  42. $a=(($b=='')?1:0);
  43. }
  44. fclose($h);
  45. return $r;
  46. }
  47. }
复制代码
三种, PHP, POST


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。