Created
September 5, 2012 11:29
-
-
Save fgnass/3635307 to your computer and use it in GitHub Desktop.
HTTP download without curl or fopen wrappers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function download($url, $timeout=10) { | |
$host; | |
$path = '/'; | |
$port = 80; | |
extract(parse_url($url)); | |
if (isset($query)) $path .= '?'.$query; | |
$req = array( | |
"GET $path HTTP/1.1", | |
"Host: $host", | |
"Connection: close", | |
"", | |
"" | |
); | |
$f = fsockopen($host, $port, $err, $errstr, $timeout); | |
if ($err) throw new Exception($errstr); | |
fwrite($f, join($req, "\r\n")); | |
while (!feof($f) && ($header = fgets($f)) !== "\r\n") { | |
if (preg_match('/^Location:\s*(.+)$/i', $header, $m)) { | |
return download($m[1]); | |
} | |
} | |
$body = ''; | |
while(!feof($f)) { | |
$body .= fread($f, 4096); | |
} | |
fclose($f); | |
return $body; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment