Force File Download with PHP

If you want to control or track your downloadable contents then a force file downloader script can give you more option. Especially if you want make images or other stemming contents like music file (mp3, wav, ogg), video files (flv, mp4, ogg, 3gpp), css, JavaScripts or even a php file downloadable then you must need to use a force file downloader script.

In this post I am going to share a simple but useful force file downloader script.


Download Source

The Download Function

/**
 * force file to download
 * 
 * @param string path to file
 */
function download($path)
{
	// if file is not readable or not exists
	if (!is_readable($path))
		die('File does not exist or it is not readable!');

	// get file's pathinfo
	$pathinfo = pathinfo($path);
	// set file name
	$file_name = $pathinfo['basename'];

	// guess mime type by extension
	$mimes = require 'mimes.php';
	$mime = isset($mimes[$pathinfo['extension']]) ? $mimes[$ext] : 'application/octet-stream';

	// set headers
	header('Pragma: public');
	header('Expires: -1');
	header('Cache-Control: public, must-revalidate, post-check=0, pre-check=0');
	header('Content-Transfer-Encoding: binary');
	header("Content-Disposition: attachment; filename=\"$file_name\"");
	header('Content-Length: ' . filesize($path));
	header("Content-Type: $mime");

	// read file as chunk to reduce memory usages
	if ( $fp = fopen($path, 'rb') ) {
		ob_end_clean();

		while( !feof($fp) and (connection_status()==0) ) {
			print(fread($fp, 8192));
			flush();
		}

		@fclose($fp);
		exit;
	}
}

Heavy memory usages is one of the most common issue of almost all force file downloader script. That's why I am not using functions like readfile. Because these files first stores whole file to the memory and then it starts download. If you want to try large files to download using this function then you will get memory limit exhausted problem. So, it is better to read a file as chunks.


Usages

$file = $_GET['file'];
download('path/'. $file);

1 comment:

Go to top