In this article i am going to explore how to download files in php from web server to local machine. Download files in php just a simple process. You do not need more lines of code to achieve that. For make easy php works with header to download and read a file. I have used below code to download any of files like zip, images, jpg, png, pdf etc. Default most of the file types (txt, jpg, png, gif, html, pdf, etc.) displayed in browser instead of download. But using php we can force browser to download these files rather showing them. In this code i am using just headers of php to force download and setting up content types. For rest of code understanding read code comments of each line of code.


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’;
}

}
}

Calling this function :- Add above function to your file and just call the download function and pass the filename like

// you can pass any file types like ex.pdf, my.png etc.
download(‘tasklist.pdf’);


You can use this script or code for download all types of files. Just put the function in your code file and pass filename and set your path of file, rest of work leave for this function. Now you are all set with how to download files in php.