I've spent quite a while trying to get stream_get_line to get a chunk encoded html file and to finish correctly at the end so that I can pipeline requests.
This is the function I have come up with.
<?php
function getURLContents($url, $ip, $port, $ssl = false, $closeConnection = false)
{
if ($ssl)
$ssl = 'ssl://';
else
$ssl = '';
$fp = pfsockopen($ssl.$ip, $port, $errno, $errstr, MAX_TIME_TO_START_CONNECTION);
if ($fp)
{
$out = 'GET '.$url." HTTP/1.1\r\n";
$out .= 'Host: '.$ip.':'.$port."\r\n";
if ($closeConnection)
$out .= "Connection: close\r\n";
else
$out .= "Connection: keep-alive\r\n";
$out .= "\r\n";
if (!fwrite($fp, $out))
{
echo 'Problem writing to socket, opening a new connection.';
fclose($fp);
$fp = pfsockopen($ssl.$ip, $port, $errno, $errstr, MAX_TIME_TO_START_CONNECTION);
fwrite($fp, $out);
}
$theData = '';
$notDone = true;
stream_set_blocking($fp, 0);
$startTime = time();
$lastTime = $startTime;
while (!feof($fp) && !$done && (($startTime + MAX_TIME_FOR_THE_RESPONSE) > time()))
{
usleep(100);
$theNewData = stream_get_line($fp, 1024, "\n");
$theData .= $theNewData;
$done = (trim($theNewData) === '0');
}
}
else
{
echo 'ERROR CONNECTING TO '.$ip.':'.$port;
return false;
}
if ($closeConnection)
fclose($fp);
return $theData;
}
?>