Skip to content

Instantly share code, notes, and snippets.

@RyadPasha
Last active July 11, 2019 15:13
Show Gist options
  • Save RyadPasha/b4561f648c91f72c3535029541aafbf2 to your computer and use it in GitHub Desktop.
Save RyadPasha/b4561f648c91f72c3535029541aafbf2 to your computer and use it in GitHub Desktop.
Download Large Files with PHP.
/**
* Download a large distant file to a local destination.
*
* This method is very memory efficient :-)
* The file can be huge, PHP doesn't load it in memory.
*
* /!\ Warning, the return value is always true, you must use === to test the response type too.
*
* @author Mohamed Riyad <@RyadPasha>
* @url: http://ryadpasha.com
* @email: me@ryadpasha.com
*
* @param string $url
* The file to download
* @param ressource $dest
* The local file path or ressource (file handler)
* @return boolean true or the error message
*/
function downloadDistantFile($url, $dest){
$options = array(
CURLOPT_FILE => is_resource($dest) ? $dest : fopen($dest, 'w'),
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_URL => $url,
CURLOPT_FAILONERROR => true, // HTTP code > 400 will throw curl error
);
$ch = curl_init();
curl_setopt_array($ch, $options);
$return = curl_exec($ch);
if($return === false){
return curl_error($ch);
} else return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment