PHP Force Download

published on April 22nd, 2008 · more from the blog →

So today I needed to force a file to download in a web browser where the browser would normally just output the file. It will also work in IE6 over a secure (HTTPS) connection.. which was a bit like hard work.

function forceDownload($file,$name=false,$contenttype="application/octet-stream",$delete=false){
	if (!$name) $name = $file;


	header("Cache-Control: public, must-revalidate");
	header("Pragma: hack");
	header("Content-Type: " . $contenttype);
	header("Content-Length: " .(string)(filesize($file)) );
	header('Content-Disposition: attachment; filename="'.basename($name).'"');
	header("Content-Transfer-Encoding: binary\n");


	$fp = fopen($file, 'rb');
	$buffer = fread($fp, filesize($file));
	fclose ($fp);
	echo $buffer;
	if ($delete){
		unlink($file);
	}
}

Example Usage:
So I wanted to create a temporary file, write some contents to it then force the file to be outputted via the browser and deleted on completion of download.
$data = 'what a load of content';    // data to write to a file


$filename = 'cache/tmpfile.txt';     // the file to write the data too, must be writable
file_put_contents($filename,$data);  // write the data to the file


// force the download and delete the file afterwards
forceDownload($filename,'whateverfilenameyoulike.txt','text/plain',true);