PHP Basics

Force download of files in PHP

If you have files on your website that you want people to download you need to change the code to allow the browser to automatically download the file. This is because if you had an image on your website that you want people to download you can have a link to this image, but this will display the image on the browser. You need to change the header request to make the browser download this file instead of displaying the image.

This is the same for PDF files and video files you need to change the header request to make the browser download the file.

Here is a small PHP snippet which you can add a function which takes one parameter of the file path. This function will then read this file and automatically download the file.

function downloadFile($file){
        $file_name = $file;
        $mime = 'application/force-download';
	header('Pragma: public'); 	// required
	header('Expires: 0');		// no cache
	header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
	header('Cache-Control: private',false);
	header('Content-Type: '.$mime);
	header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
	header('Content-Transfer-Encoding: binary');
	header('Connection: close');
	readfile($file_name);
	exit();
}
Back to top

Learn how to code with Treehouse

  • Learn projects with access to 1000+ videos
  • Practice live with our Code Challenge Engine
  • Get help in our members-only forums

Start with a 7 day free trial