欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php 模拟post请求

程序员文章站 2022-04-26 22:17:18
...
  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=array()){//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. }
  48. $url='http://******/con/Inter.php';
  49. $data=Request::post($url,array('api'=>'tag_list'));
  50. $data2=Request::post2($url,array('api'=>'tag_list'));
  51. echo $data;
复制代码

php, post