Skip to content

Instantly share code, notes, and snippets.

@eric1234
Last active October 19, 2016 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eric1234/37fd102798d99d94b0dcebde6bb29ef3 to your computer and use it in GitHub Desktop.
Save eric1234/37fd102798d99d94b0dcebde6bb29ef3 to your computer and use it in GitHub Desktop.
Simple download function for PHP

Usage

$url = 'http://some.url/file.txt';
$data = download($url, $headers, $err_msg);
if( !$data ) {
  echo $err_msg;
  die;
}

print_r($headers);
echo stream_get_contents($data);

This is conceptually similar to:

echo stream_get_contents(fopen($url, 'r'))

The differences are:

  • We can get better error info.
  • We can get the HTTP headers so we know things like the content type.
  • Since we are using the curl library it works even when fopen doesn't allow URLs.
<?php
# https://gist.github.com/eric1234/37fd102798d99d94b0dcebde6bb29ef3
#
# Abstracts the idiocy of the CURL API for something simpler. Assumes we are
# downloading data (so a GET request) and we need no special request headers.
# Returns an IO stream which will be the data requested. The headers of the
# response will be stored in the $headers param reference.
#
# If the request fails for some reason FALSE is returned with the $err_msg
# param containing more info.
function download($url, &$headers=[], &$err_msg) {
$io = curl_init($url);
$stream = fopen('php://temp', 'w+');
curl_setopt_array($io, [
CURLOPT_FAILONERROR => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HEADER => true,
CURLOPT_FILE => $stream,
]);
if( curl_exec($io) === false ) {
$err_msg << curl_error($io);
return false;
}
curl_close($io);
rewind($stream);
$line = trim(fgets($stream));
if( preg_match('/^HTTP\/([^ ]+) (.*)/i', $line, $matches) ) {
$headers['HTTP_VERSION'] = $matches[1];
$headers['STATUS'] = $matches[2];
}
while( $line = fgets($stream) ) {
if( preg_match('/^\s+$/', $line) ) break;
list($key, $value) = preg_split('/\s*:\s*/', $line, 2);
$headers[strtoupper($key)] = trim($value);
}
return $stream;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment