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 依存関係があり、移植性の高いコードが必要なため、使用したくありません。
関数が元の HTML を返すことができるように、HTTP チャンクでエンコードされた文字列を簡単にデコードする方法は? Content-Length:
また、デコードされた文字列の長さがヘッダーと一致することを確認する必要があります。
どんな助けでも大歓迎です。ありがとう。