Force File Download

Posted by Pete | Posted in PHP Functions | Posted on 29-08-2009-05-2008

0

So you’ve got a file, but its not a .zip or .rar etc which automatically downloads through the browser, its a file such as .txt which opens up in the browser but you want it to be downloaded to the users computer automatically. Well this function will allow you to force the browser to accept it as a file to force download.

This function will allow the download of the files but will not allow any directories to be downloaded.

function downloadfile($file){ // Start Function
	$file = "/downloads/". $file; //Set File Location
	if (file_exists($file)) { // Check if file exists
		if(!is_dir($file)){ // Check if it is a directory or a file
			// The following files will set the headers to the file download
		    header('Content-Description: File Transfer');
		    header('Content-Type: application/octet-stream');
		    header('Content-Disposition: attachment; filename='.basename($file));
		    header('Content-Transfer-Encoding: binary');
		    header('Expires: 0');
		    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		    header('Pragma: public');
		    header('Content-Length: ' . filesize($file));
		    ob_clean(); // Clear any set cookies/headers.
		    flush(); // Flush
		    readfile($file); // Actually Start The Download
		    return "Downloading $file"; // Return Downloading FILE_NAME
		    exit; // Stop Processing
		}else{ // If file is a directory
			return "You have selected to download a directory. Download Cancelled"; // Show error
		}
	}else{ // If file doesnt exist
		return "File doesnt exist";
	}
}

Please note that this function requires the use of ob_start(); at the top of the page just after

So now you need to run it, below is an example

testdownload.zip is located in downloads/ folder. As I said in my previous post sorry for the lack of tutorials in the past couple of weeks, but I am back and will post more in the coming weeks. If you need any more help with this tutorial or want to leave some feedback please leave a comment below. Your comments and feedback can also help others.

Write a comment

You must be logged in to post a comment.

Tutorials Written By Peter Kelly