PHP

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 ^

Join Paulund

  • Get access to 100s of premium tutorials and downloadable content
  • Members content consists of Premium WordPress plugins, CSS packages, jQuery packages, tutorial demo files and templates for 100s of web development tutorials
  • In-depth development tutorials
  • Priority tutorial requests
  • Priority email development support
  • No ads

Here at Paulund you'll find Web Development tutorials and snippets focusing mainly on PHP, WordPress and CSS. Members will get access to premium tutorials that go into more detail about development with these languages. You will also get access to downloadable premium content based on the tutorial.

Join Paulund