I want to make HTTP request without having dependency to cURL and allow_url_fopen = 1
by opening socket connection and send raw HTTP request:
/**
* 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;
}
The function works ok, but since I'm using HTTP/1.1, the response body usually returned in Chunked-encoded string. For example (from Wikipedia):
25
This is the data in the first chunk
1C
and this is the second one
3
con
8
sequence
0
I don't want to use http_chunked_decode()
since it has PECL dependency and I want a highly portable code.
How to easily decode HTTP-chunked encoded string so my function can return the original HTML? I also have to make sure that the length of the decoded string match with the Content-Length:
header.
Any help would be appreciated. Thanks.
I don't know if it's optimal for you what you need to do but, if you specify
HTTP/1.0
instead ofHTTP/1.1
, you will not get a chunked response.this Function use in Wordpress.
Since the function returns the HTTP response header, you should check if
'Transfer-Encoding'
is'chunked'
then decode the chunked-encoded string. In pseudocode:Parsing HTTP response header:
Below is the function to parse HTTP response header to associative array.
The function will return an array like this:
Notice how the
Set-Cookie
headers parsed to array. You need to parse the cookies later to associate a URL with the cookies need to be sent.Decode the chunked-encoded string
The function below take the chunked-encoded string as the argument, and return the decoded string.