Over a million developers have joined DZone.

PHP Force Download - Keep Up With What's Going Down

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

A force-download script can give you more control over a file download than you would have providing a direct link. Using a force-download script, you can:

  • Validate that a person is logged in
  • Increment a counter in a text file
  • Connect to your database and log IP information, increment a counter, and record who downloaded the file.

The Code

// grab the requested file's name
$file_name = $_GET['file'];

// make sure it's a file before doing anything!

		Do any processing you'd like here:
		1.  Increment a counter
		2.  Do something with the DB
		3.  Check user permissions
		4.  Anything you want!

	// required for IE
	if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off');	}

	// get the file mime type using the file extension
		case 'pdf': $mime = 'application/pdf'; break;
		case 'zip': $mime = 'application/zip'; break;
		case 'jpeg':
		case 'jpg': $mime = 'image/jpg'; break;
		default: $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('Content-Length: '.filesize($file_name));	// provide file size
	readfile($file_name);		// push it out


This file alone isn't secure. You will want to validate that the file doesn't provide access to your website code, files you don't want downloaded, and so on. That code will be specific to your website and needs.

Do you use a force-download script? What processing do you do inside the script?

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}