当前位置:Gxlcms > PHP教程 > PHP发送POST请求

PHP发送POST请求

时间:2021-07-01 10:21:17 帮助过:19人阅读

  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. $postdata = http_build_query($post_data);
  9. $options = array(
  10. 'http' => array(
  11. 'method' => 'POST',
  12. 'header' => 'Content-type:application/x-www-form-urlencoded',
  13. 'content' => $postdata,
  14. 'timeout' => 15 * 60 // 超时时间(单位:s)
  15. )
  16. );
  17. $context = stream_context_create($options);
  18. $result = file_get_contents($url, false, $context);
  19. return $result;
  20. }
  21. //使用方法
  22. $post_data = array(
  23. 'username' => 'stclair2201',
  24. 'password' => 'handan'
  25. );
  26. send_post('http://www.qianyunlai.com', $post_data);
  27. /**
  28. * Socket版本
  29. * 使用方法:
  30. * $post_string = "app=socket&version=beta";
  31. * request_by_socket('chajia8.com', '/restServer.php', $post_string);
  32. */
  33. function request_by_socket($remote_server,$remote_path,$post_string,$port = 80,$timeout = 30) {
  34. $socket = fsockopen($remote_server, $port, $errno, $errstr, $timeout);
  35. if (!$socket) die("$errstr($errno)");
  36. fwrite($socket, "POST $remote_path HTTP/1.0");
  37. fwrite($socket, "User-Agent: Socket Example");
  38. fwrite($socket, "HOST: $remote_server");
  39. fwrite($socket, "Content-type: application/x-www-form-urlencoded");
  40. fwrite($socket, "Content-length: " . (strlen($post_string) + 8) . "");
  41. fwrite($socket, "Accept:*/*");
  42. fwrite($socket, "");
  43. fwrite($socket, "mypost=$post_string");
  44. fwrite($socket, "");
  45. $header = "";
  46. while ($str = trim(fgets($socket, 4096))) {
  47. $header .= $str;
  48. }
  49. $data = "";
  50. while (!feof($socket)) {
  51. $data .= fgets($socket, 4096);
  52. }
  53. return $data;
  54. }
  55. ?>
  56. /**
  57. * Curl版本
  58. * 使用方法:
  59. * $post_string = "app=request&version=beta";
  60. * request_by_curl('http://www.qianyunlai.com/restServer.php', $post_string);
  61. */
  62. function request_by_curl($remote_server, $post_string) {
  63. $ch = curl_init();
  64. curl_setopt($ch, CURLOPT_URL, $remote_server);
  65. curl_setopt($ch, CURLOPT_POSTFIELDS, 'mypost=' . $post_string);
  66. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  67. curl_setopt($ch, CURLOPT_USERAGENT, "qianyunlai.com's CURL Example beta");
  68. $data = curl_exec($ch);
  69. curl_close($ch);
  70. return $data;
  71. }
  72. ?>

原文地址:http://blog.sjzycxx.cn/post/435/

以上就介绍了PHP发送POST请求,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

人气教程排行