PHP Download file snippet
Many of us like to share files publicly on our websites, pointing directly to downloadable contents! But this can be risky as you might be exposing stuff you wouldn't want public to know. Instead of pointing to downloadable files directly, you can use this PHP snippet to force download them. This way the original file path will be hidden from the public and you'll feel bit secure. Just copy paste this function into a PHP file and call it when needed.PHP
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
function force_download_a_file($dl_file)
{
if(is_file($dl_file))
{
if(ini_get('zlib.output_compression')) {
ini_set('zlib.output_compression', 'Off');
}
header('Expires: 0');
header('Pragma: public');
header('Cache-Control: private',false);
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="'.basename($dl_file).'"');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($dl_file)).' GMT');
header('Content-Length: '.filesize($dl_file));
header('Connection: close');
readfile($dl_file);
die();
}
}
PHP
- 1
force_download_a_file('home/Websites/path/content.pdf');