Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

86 righe
2.7 KiB

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: wangxj
  5. * Date: 2017/1/17
  6. * Time: 19:08
  7. */
  8. namespace common\components;
  9. class zHttp
  10. {
  11. /**
  12. * User: wangxj
  13. *
  14. * 发送http请求
  15. * http://php.net/manual/en/curl.examples-basic.php
  16. *
  17. * @params string $url
  18. * @params array $data
  19. *
  20. * @return
  21. */
  22. public static function httpRequest($url, $data = [], $header = [])
  23. {
  24. // Initialize cURL
  25. $ch = curl_init();
  26. //如果url地址指向的是本地域名,etc/hosts域名指向本机192的ip地址,不要指向127.0.0.1
  27. //windows phpstudy nginx 本地无法发送请求,由于php-cgi监听的9000端口只能单线程,当发送curl请求时,
  28. //php-cgi会占用9000端口,但是请求的url是又本地的,这时它想执行php程序时,由于php-cgi占用9000,所以会一直等待,死循环
  29. // Set URL on which you want to post the Form and/or data
  30. if ($header !== []) {
  31. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  32. }
  33. curl_setopt($ch, CURLOPT_URL, $url);
  34. // Data+Files to be posted
  35. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  36. // Pass TRUE or 1 if you want to wait for and catch the response against the request made
  37. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  38. // For Debug mode; shows up any error encountered during the operation
  39. curl_setopt($ch, CURLOPT_VERBOSE, 1);
  40. curl_setopt($ch, CURLOPT_TIMEOUT, 120);
  41. // Execute the request
  42. $response = curl_exec($ch);
  43. // Just for debug: to see response
  44. return $response;
  45. }
  46. /**
  47. * Notes:异步请求
  48. * User: Steven
  49. * Date: 2018/1/17
  50. * Time: 15:08
  51. * @param $type
  52. * @param $url
  53. * @param $param
  54. */
  55. public static function syncRequest($type, $url, $param)
  56. {
  57. $url_info = parse_url($url);
  58. $query = empty($param) ? '' : http_build_query($param);
  59. $port = 80;
  60. $errno = 0;
  61. $errstr = '';
  62. $fp = fsockopen($url_info['host'], $port, $errno, $errstr);
  63. if ($type == 1) {
  64. $out = "GET " . $url_info['path'] . "?" . $query . " HTTP/1.1\r\n";
  65. $out .= "host:" . $url_info['host'] . "\r\n\r\n";
  66. } elseif ($type == 2) {
  67. $out = "POST " . $url_info['path'] . " HTTP/1.1\r\n";
  68. $out .= "host:" . $url_info['host'] . "\r\n";
  69. $out .= "content-length:" . strlen($query) . "\r\n";
  70. $out .= "content-type:application/x-www-form-urlencoded\r\n";
  71. $out .= "connection:close\r\n\r\n";
  72. $out .= $query;
  73. } else {
  74. //其他请求类型处理
  75. $out = '';
  76. }
  77. fputs($fp, $out);
  78. fclose($fp);
  79. }
  80. }