note 82843 deleted from features.remote-files by nlopess

From: Date: Tue, 29 Apr 2008 09:08:35 +0000
Subject: note 82843 deleted from features.remote-files by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-138891@lists.php.net to get a copy of this message
Note Submitter: mail at 3v1n0 dot net ---- This is a function that works like fopen/fread for remote HTTP files but that supports the HTTP resume. Calling http_get_resume(http://any-url.com) simply it will output the http content (it doesn't support any http 3xx, 4xx, 5xx error, but they could be easily managed). Calling http_get_resume(http://any-url.com, 10) it will output the http content starting from the 10th byte (as many download managers do; I've tested with wget)... I had to write since the fopen() function doesn't support fseek() for remote files, and this is a good workaround. <? function http_get_resume($url, $range = 0) { $url_stuff = parse_url($url); $port = isset($url_stuff['port']) ? $url_stuff['port'] : 80; $fp = @fsockopen($url_stuff['host'], $port); if (!$fp) return false; $query = 'GET '.$url_stuff['path'].'?'.$url_stuff['query']." HTTP/1.1\r\n"; $query .= 'Host: '.$url_stuff['host']."\r\n"; $query .= 'Connection: close'."\r\n"; $query .= 'Cache-Control: no'."\r\n"; $query .= 'Accept-Ranges: bytes'."\r\n"; if ($range != 0) $query .= 'Range: bytes='.$range.'-'."\r\n"; // -500 //$query .= 'Referer: http://php.net'."\r\n"; //$query .= 'User-Agent: yourAgent'."\r\n"; $query .= "\r\n"; fwrite($fp, $query); $chunksize = 1024*1024; $headersfound = false; while (!feof($fp) && !$headersfound) { $buffer .= @fread($fp, 1); if (preg_match('/HTTP\/[0-9]\.[0-9][ ]+([0-9]{3}).*\r\n/', $buffer, $matches) || preg_match('/[^:][A-Za-z_-]:.*\r\n/', $buffer)) { if (!preg_match('/2[0-9]{2}/', $matches[1])) return false; $headers[] = $buffer; $buffer = ''; } else if (preg_match('/^\r\n/', $buffer)) { $headersfound = true; $buffer = ''; } if (strlen($buffer) >= $chunksize) return false; } while (!feof($fp) && $headersfound) { $buffer = @fread($fp, $chunksize); echo $buffer; ob_flush(); flush(); } $status = fclose($fp); return $status; } ?>

« previous php.notes (#138891) next »