Skip to content

Instantly share code, notes, and snippets.

@baras
Forked from brasofilo/download.php
Last active October 20, 2021 07:00
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 baras/4834ae2ae8faae4cf933bdf7635709a4 to your computer and use it in GitHub Desktop.
Save baras/4834ae2ae8faae4cf933bdf7635709a4 to your computer and use it in GitHub Desktop.
Force File Download with PHP
<?php
/*
* Force File Download.
* Usage: http://example.com/download.php?file=./uploads/image.jpg
*
* There are a couple of *ninja* exit() as security guarantee, adapt as necessary.
*
*/
// Grab the requested file's name.
$file_name = filter_input(INPUT_GET, 'file', FILTER_SANITIZE_STRING);
// Make sure it's a file before doing anything!
if (!is_file($file_name)) {
http_response_code(404);
exit;
}
// Required for IE.
if (ini_get('zlib.output_compression')) {
ini_set('zlib.output_compression', 'Off');
}
// Get the file mime type using the file extension.
switch (strtolower(substr(strrchr($file_name, '.'), 1))) {
case 'pdf':
$mime = 'application/pdf';
break;
case 'zip':
$mime = 'application/zip';
break;
case 'jpeg':
case 'jpg':
$mime = 'image/jpg';
break;
case 'mp3':
$mime = 'audio/mpeg3';
break;
default:
exit();
}
header('Pragma: public'); // Required.
header('Expires: 0'); // No cache.
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($file_name)) . ' GMT');
header('Cache-Control: private', false);
header('Content-Type: ' . $mime);
header('Content-Disposition: attachment; filename="' . basename($file_name) . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file_name)); // Provide file size.
header('Connection: close');
readfile($file_name); // Push it out.
exit();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment