/** * 使用fsockopen发送URL请求 * @param $url * @param $method: GET、POST等 * @param array $params * @param array $header * @param int $timeout * @return array|bool */ function sendHttpRequest($url, $method = 'GET', $params = [], $header = [], $timeout = 30) { $urlInfo = parse_url($url); if (isset($urlInfo['scheme']) && strcasecmp($urlInfo['scheme'], 'https') === 0) //HTTPS { $prefix = 'ssl://'; $port = 443; } else { //HTTP $prefix = 'tcp://'; $port = isset($urlInfo['port']) ? $urlInfo['port'] : 80; } $host = $urlInfo['host']; $path = isset($urlInfo['path']) ? $urlInfo['path'] : '/'; if (!empty($params) && is_array($params)) { $params = http_build_query($params); } $contentType = ''; $contentLength = ''; $requestBody = ''; if ($method === 'GET') { $params = $params ? '?' . $params : ''; $path .= $params; } else { $requestBody = $params; $contentType = "Content-Type: application/x-www-form-urlencoded\r\n"; $contentLength = "Content-Length: " . strlen($requestBody) . "\r\n"; } $auth = ''; if (!empty($urlInfo['user'])) { $auth = 'Authorization: Basic ' . base64_encode($urlInfo['user'] . ':' . $urlInfo['pass']) . "\r\n"; } if ($header && is_array($header)) { $tmpString = ''; foreach ($header as $key => $value) { $tmpString .= $key . ': ' . $value . "\r\n"; } $header = $tmpString; } else { $header = ''; } $out = "$method $path HTTP/1.1\r\n"; $out .= "Host: $host\r\n"; $out .= $auth; $out .= $header; $out .= $contentType; $out .= $contentLength; $out .= "Connection: Close\r\n\r\n"; $out .= $requestBody;//post发送数据前必须要有两个换行符\r\n $fp = fsockopen($prefix . $host, $port, $errno, $errstr, $timeout); if (!$fp) { return false; } if (!fwrite($fp, $out)) { return false; } $response = ''; while (!feof($fp)) { $response .= fread($fp, 1024); } if (!$response) { return false; } fclose($fp); $separator = '/\r\n\r\n|\n\n|\r\r/'; list($responseHeader, $responseBody) = preg_split($separator, $response, 2); $httpResponse = array( 'header' => $responseHeader, 'body' => $responseBody ); return $httpResponse; }
php 异步请求
最新推荐文章于 2023-11-25 08:49:17 发布