|
- <?php
- /**
- * Created by PhpStorm.
- * User: wangxj
- * Date: 2017/1/17
- * Time: 19:08
- */
-
- namespace common\components;
-
- class zHttp
- {
- /**
- * User: wangxj
- *
- * 发送http请求
- * http://php.net/manual/en/curl.examples-basic.php
- *
- * @params string $url
- * @params array $data
- *
- * @return
- */
- public static function httpRequest($url, $data = [], $header = [])
- {
- // Initialize cURL
- $ch = curl_init();
-
- //如果url地址指向的是本地域名,etc/hosts域名指向本机192的ip地址,不要指向127.0.0.1
- //windows phpstudy nginx 本地无法发送请求,由于php-cgi监听的9000端口只能单线程,当发送curl请求时,
- //php-cgi会占用9000端口,但是请求的url是又本地的,这时它想执行php程序时,由于php-cgi占用9000,所以会一直等待,死循环
- // Set URL on which you want to post the Form and/or data
- if ($header !== []) {
- curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
- }
- curl_setopt($ch, CURLOPT_URL, $url);
- // Data+Files to be posted
- curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
- // Pass TRUE or 1 if you want to wait for and catch the response against the request made
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- // For Debug mode; shows up any error encountered during the operation
- curl_setopt($ch, CURLOPT_VERBOSE, 1);
- curl_setopt($ch, CURLOPT_TIMEOUT, 120);
- // Execute the request
- $response = curl_exec($ch);
-
- // Just for debug: to see response
- return $response;
- }
-
-
- /**
- * Notes:异步请求
- * User: Steven
- * Date: 2018/1/17
- * Time: 15:08
- * @param $type
- * @param $url
- * @param $param
- */
- public static function syncRequest($type, $url, $param)
- {
- $url_info = parse_url($url);
- $query = empty($param) ? '' : http_build_query($param);
- $port = 80;
- $errno = 0;
- $errstr = '';
- $fp = fsockopen($url_info['host'], $port, $errno, $errstr);
- if ($type == 1) {
- $out = "GET " . $url_info['path'] . "?" . $query . " HTTP/1.1\r\n";
- $out .= "host:" . $url_info['host'] . "\r\n\r\n";
- } elseif ($type == 2) {
- $out = "POST " . $url_info['path'] . " HTTP/1.1\r\n";
- $out .= "host:" . $url_info['host'] . "\r\n";
- $out .= "content-length:" . strlen($query) . "\r\n";
- $out .= "content-type:application/x-www-form-urlencoded\r\n";
- $out .= "connection:close\r\n\r\n";
- $out .= $query;
- } else {
- //其他请求类型处理
- $out = '';
- }
- fputs($fp, $out);
- fclose($fp);
- }
- }
|