PHP Force File Download Script

PHP Force File Download Script

The following is the script to force PHP to download a file, so that you can have customised file download, rather than have the link directly to the file to be downloaded. One of the examples you want to use this code is when you want to record the number of people are trying to download the file you provided.

$fileName = "file_name.pdf";
$filePath = $fileName;
$fileSize = filesize($filePath);

header("HTTP/1.1 200 OK");
header("Status: 200 OK");
header("Content-Type: application/force-download");
header("Content-Disposition: attachment;
filename='$fileName'");
header("Content-Length: $fileSize");
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Expires: 0");

readfile($filePath);

Be sure that the line bolded is a must if you want the script to be working in both IE and Firefox. My experience is that without that line, IE will give you an error saying that file could not be found.

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *

My new Snowflake Blog is now live. I will not be updating this blog anymore but will continue with new contents in the Snowflake world!