Skip to content

Instantly share code, notes, and snippets.

@rpowis
Last active October 5, 2021 22:44
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rpowis/4667115 to your computer and use it in GitHub Desktop.
Save rpowis/4667115 to your computer and use it in GitHub Desktop.
Check for remote file and force the user to download if it exists.
$file = 'http://www.example.com/path/to/file.ext';
$headers = array_change_key_case(get_headers($file, TRUE));
$filesize = $headers['content-length'][1];
if ( $headers[0] != 'HTTP/1.1 404 Not Found' ) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . $filesize);
echo "downloading";
ob_clean();
flush();
readfile($file);
exit;
}
while(1) {
Echo "\n";
if ( connection_status() != 0 ) {
die;
}
}
@sanishan
Copy link

is there a way it download file in chunk and deliver in chunk? so no memory overflow?

@adnanhz
Copy link

adnanhz commented Feb 25, 2019

This works but I had to replace $filesize = $headers['content-length'][1]; with $filesize = $headers['content-length'];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment