function rex_a657_open_http_socket($url, &$errno, &$errstr, $timeout)
{
    $buf = '';
    $parts = parse_url($url);
    $port = isset($parts['port']) ? $parts['port'] : 80;
    $path = isset($parts['path']) ? $parts['path'] : '/';
    // use timeout for opening connection
    $fp = fsockopen($parts['host'], $port, $errno, $errstr, $timeout);
    if ($fp) {
        // allow write/read timeouts
        stream_set_timeout($fp, $timeout);
        $out = '';
        $out .= 'GET ' . $path . " HTTP/1.1\r\n";
        $out .= 'Host: ' . $parts['host'] . "\r\n";
        $out .= "Connection: Close\r\n\r\n";
        fwrite($fp, $out);
        // check write timeout
        $info = stream_get_meta_data($fp);
        if ($info['timed_out']) {
            return false;
        }
        $httpHead = '';
        while (!feof($fp)) {
            $buf .= fgets($fp, 512);
            if ($httpHead == '' && ($headEnd = strpos($buf, "\r\n\r\n")) !== false) {
                $httpHead = substr($buf, 0, $headEnd);
                // extract http header
                $buf = substr($buf, $headEnd + 4);
                // trim buf to contain only http data
            }
        }
        fclose($fp);
        $chunked = false;
        foreach (explode("\r\n", $httpHead) as $headPart) {
            $headPart = strtolower($headPart);
            if (strpos($headPart, 'http') !== false) {
                $mainHeader = explode(' ', $headPart);
                if ($mainHeader[1] !== '200') {
                    $errno = $mainHeader[1];
                    $errstr = $mainHeader[2];
                    return false;
                }
            } elseif (strpos($headPart, 'transfer-encoding: chunked') !== false) {
                $chunked = true;
            }
        }
        if ($chunked) {
            $buf = unchunkHttp11($buf);
        }
    } else {
        return false;
    }
    return $buf;
}
Example #2
0
$fp = fsockopen("wimg.ca", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "{$errstr} ({$errno})<br />\n";
} else {
    $out = "GET /http://www.nu.nl HTTP/1.0\r\n";
    $out .= "Host: wimg.ca\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    while (!feof($fp)) {
        $reply .= fgets($fp, 1024);
    }
    fclose($fp);
}
$data = substr($reply, strpos($reply, "\r\n\r\n") + 4);
if (strpos(strtolower($reply), "transfer-encoding: chunked") !== FALSE) {
    $data = unchunkHttp11($data);
}
header('Content-Type: image/png');
echo $data;
die;
// standard routines cannot handle chunked data...
// the below does not work
$url = 'http://wimg.ca/http://www.nu.nl';
$img_with_headers = file_get_contents($url);
$i = strpos($img_with_headers, "PNG");
header('Content-Type: image/png');
echo substr($img_with_headers, $i - 1);
die;
$i = strpos($img_with_headers, "\r\n\r\n");
die(substring($img_with_headers, 0, $i + 7));
$img = substr($img_with_headers, $i + 4);