note 36703 added to function.fsockopen
| From: | richardaburton at hotmail dot com | Date: | Sun, 19 Oct 2003 12:29:09 +0000 |
| Subject: | note 36703 added to function.fsockopen | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-58884@lists.php.net to get a copy of this message | ||
Improved HTTP/1.1 chunked transfer-encoding example.
The sample code given below by Jack does not function correctly when run against a recent version of
Apache (I'm assuming that this did once work, but from the HTTP/1.1 spec I can only assume if
it did work it was based mostly on luck).
<?php
$header = "";
$response = "";
// connect
if (!($request=fsockopen('whatever.com',80,$errno,$errstr))) exit($errstr);
else {
socket_set_timeout($request,10);
// send request
fwrite($request,$post);
// get header
do $header.=fread($request,1); while (!preg_match('/\\r\\n\\r\\n$/',$header));
// check for chunked encoding
if (preg_match('/Transfer\\-Encoding:\\s+chunked\\r\\n/',$header))
do {
$byte = "";
$chunk_size="";
do {
$chunk_size.=$byte;
$byte=fread($request,1);
} while ($byte!="\\r"); // till we match the CR
fread($request, 1); // also drop off the LF
$chunk_size=hexdec($chunk_size); // convert to real number
$response.=fread($request,$chunk_size);
fread($request,2); // ditch the CRLF that trails the chunk
} while ($chunk_size); // till we reach the 0 length chunk (end marker)
else {
// check for specified content length
if (preg_match('/Content\\-Length:\\s+([0-9]*)\\r\\n/',$header,$matches)) {
$response=fread($request,$matches[1]);
} else {
// not a nice way to do it (may also result in extra CRLF which trails the real content???)
while (!feof($request)) $response .= fread($request, 4096);
}
}
// close connection
fclose($request);
}
// do something useful with the response
print($header);
print($response);
?>
Richard.
----
Manual Page -- http://www.php.net/manual/en/function.fsockopen.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+36703
Delete -- http://master.php.net/manage/user-notes.php?action=delete+36703&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+36703&report=yes
Search -- http://master.php.net/manage/user-notes.php