我想在不依赖 cURL 的情况下发出 HTTP 请求,并allow_url_fopen = 1
通过打开套接字连接并发送原始 HTTP 请求:
/**
* Make HTTP GET request
*
* @param string the URL
* @param int will be filled with HTTP response status code
* @param string will be filled with HTTP response header
* @return string HTTP response body
*/
function http_get_request($url, &$http_code = '', &$res_head = '')
{
$scheme = $host = $user = $pass = $query = $fragment = '';
$path = '/';
$port = substr($url, 0, 5) == 'https' ? 443 : 80;
extract(parse_url($url));
$path .= ($query ? "?$query" : '').($fragment ? "#$fragment" : '');
$head = "GET $path HTTP/1.1\r\n"
. "Host: $host\r\n"
. "Authorization: Basic ".base64_encode("$user:$pass")."\r\n"
. "Connection: close\r\n\r\n";
$fp = fsockopen($scheme == 'https' ? "ssl://$host" : $host, $port) or
die('Cannot connect!');
fputs($fp, $head);
while(!feof($fp)) {
$res .= fgets($fp, 4096);
}
fclose($fp);
list($res_head, $res_body) = explode("\r\n\r\n", $res, 2);
list(, $http_code, ) = explode(' ', $res_head, 3);
return $res_body;
}
该函数工作正常,但由于我使用的是 HTTP/1.1,因此响应正文通常以块编码字符串返回。例如(来自维基百科):
25
This is the data in the first chunk
1C
and this is the second one
3
con
8
sequence
0
我不想使用http_chunked_decode()
,因为它具有 PECL 依赖项,并且我想要一个高度可移植的代码。
如何轻松解码 HTTP 分块编码字符串,以便我的函数可以返回原始 HTML?我还必须确保解码字符串的长度与Content-Length:
标题匹配。
任何帮助,将不胜感激。谢谢。