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.

Leave a Reply

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