Skip to content

Instantly share code, notes, and snippets.

@fgnass
Created September 5, 2012 11:29
Show Gist options
  • Save fgnass/3635307 to your computer and use it in GitHub Desktop.
Save fgnass/3635307 to your computer and use it in GitHub Desktop.
HTTP download without curl or fopen wrappers
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