Skip to content

Instantly share code, notes, and snippets.

@adisheikh121
Created May 5, 2017 12:52
Show Gist options
  • Save adisheikh121/562122bc4bcfd14b7e3f3dd7da142f45 to your computer and use it in GitHub Desktop.
Save adisheikh121/562122bc4bcfd14b7e3f3dd7da142f45 to your computer and use it in GitHub Desktop.
How to download files in PHP
<?php
download('tasklist.pdf');
function download($filename){
if(!empty($filename)){
// Specify file path.
$path = ''; // '/uplods/'
$download_file = $path.$filename;
// Check file is exists on given path.
if(file_exists($download_file))
{
// Getting file extension.
$extension = explode('.',$filename);
$extension = $extension[count($extension)-1];
// For Gecko browsers
header('Content-Transfer-Encoding: binary');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($path)) . ' GMT');
// Supports for download resume
header('Accept-Ranges: bytes');
// Calculate File size
header('Content-Length: ' . filesize($download_file));
header('Content-Encoding: none');
// Change the mime type if the file is not PDF
header('Content-Type: application/'.$extension);
// Make the browser display the Save As dialog
header('Content-Disposition: attachment; filename=' . $filename);
readfile($download_file);
exit;
}
else
{
echo 'File does not exists on given path';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment