I've put together a download script (called file.php
) using headers and readfile()
, the actual download logic being as follows:
header("Content-type: " . mime_content_type($path));
header("Content-Length: " . filesize($path));
header('Content-Disposition: attachment; filename="' . $fileName . '"');
ob_clean();
flush();
readfile($path);
Before this, there's about 30 lines of mysqli-access, to get the file info from db. Only one block of php, no html output (except for the occasional echo upon exception, but they're not called).
This works splendid in my local environment, the file is force-downloaded correctly. However, when I upload it to my site (shared hosting), it opens the files directly in the browser, which won't work.
I've played around quite a bit with it, and found that if I put only the logic above in a separate file (with the addition of query params for the variables needed), it works.
I don't like it, but decided to roll with it. To that end I replaced the download-logic in my file.php
with header("Location: download.php?path={path}&fileName={fileName});"
, where download.php
contains only the download logic.
Again, works splendid locally, but once I've put it on the host, it does not work. However, this time it's the header("Location:...");
that doesn't work. Accessing download.php
directly does.
So I've come to the conclusion that the problem is with the headers not taking effect, rather than the download code itself. I'm using headers in other scripts, and they work fine, it's just this one script.
I've seen various explanations as to why this might happen, but can't find any that apply to this situation, especially not since it works in one environment but not the other.
Any ideas would be most welcome.