if (strpos($headers, 'Transfer-Encoding: chunked') !== false) {
$response = '';
while (!feof($socket)) {
// Read the chunk size (in hexadecimal)
$chunkSizeHex = rtrim(fgets($socket));
// Convert the chunk size to an integer
$chunkSize = hexdec($chunkSizeHex);
// If the chunk size is 0, it means we've reached the last chunk
if ($chunkSize === 0) {
break;
}
// Read the chunk data
$chunkData = '';
while ($chunkSize > 0) {
$buffer = fread($socket, $chunkSize);
$chunkData .= $buffer;
$chunkSize -= strlen($buffer);
}
// Add the chunk data to the response
$response .= $chunkData;
// Read the trailing CRLF after the chunk data
fgets($socket);
}
} else {
// If the response is not chunked, read the response normally
while (!feof($socket)) {
$response .= fread($socket, 128);
}
}