PHP download page: file_exists() returns true, but browser returns 'page not found'
- by Chris
I'm using PHP for a file download page. Here's a snippet of the problem code:
if (file_exists($attachment_location)) {
header($_SERVER["SERVER_PROTOCOL"] . " 200 OK");
header("Cache-Control: public"); // needed for i.e.
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: Binary");
header("Content-Length:".filesize($attachment_location));
header("Content-Disposition: attachment; filename=file.zip");
readfile($attachment_location);
die("Hooray");
}
else {
die("Error: File not found.");
}
This code works absolutely fine when testing locally, but after deploying to the live server the browser returns a 'Page not found' error. I thought it might be an .htaccess issue, but all .htaccess files on the live server are identical to their local counterparts. My next guess would be the live server's PHP configuration, but I have no idea what PHP setting might cause this behaviour.
The file_exists() function always returns true - I've checked this on the live server and it's always correctly picking up the file, its size etc., so it does have a handle on the file. It just won't perform the download!
The main site is a Wordpress site, but this code isn't part of a Wordpress page - it's in a standalone directory within the site root.
UPDATE: is_file() and is_readable() are both returning true for the file, so that's not the problem. The specific line that is causing the problem is:
readfile($attachment_location)
Everything up until that point is super happy.