PHP 8.5.0 RC 1 available for testing

Voting

: four plus three?
(Example: nine)

The Note You're Voting On

richardaburton at hotmail dot com
21 years ago
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('example.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.

<< Back to user notes page

To Top