I'm having trouble with downloading a file from a hashed filepath.
I'm using a MySQL database where I store various data from a HTML form. It is possible to upload up to three different files. These are moved to a uploads folder on the server. I’m using MD5 to prevent duplicate file uploads.
All the data in the database gets called from an other script. There is an amount of download links shown, depending on how much files are uploaded. Im using fileinfo and headers to determine the mimetype and to download the file. But all I get when downloading is some zipfile with random folders and documents or a non-extension file which, giving the right extension, opens with warnings and ultimately shows the correct file.
Here is my download code:
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
print("</br>"); echo finfo_file($finfo, $_GET["fName"]);
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename= ". $_GET["fName"]);
header("Content-Type: " .$finfo);
finfo_close($finfo);
header("Content-Transfer-Encoding: binary");
// Read the file from disk
readfile($_GET["fName"]);
The $_GET["fName"]
is a variable passed by a link which contains the specified pathname(example: ./uploads/hashcode
). How can I make this so that I can download the document correctly? As in download the document whole, not some ZIP file or a non-extension file.
I’ve been fighting with this problem for some days now (searched on internet to find something usable) and im getting quite desperate.
Additional note: Most times the file that downloads is the correct file from my server. It has the same name as the hash files in the uploads folder. But it doesnt have any extension.
Let's say $_GET["fName"] is /uploads/randomhash/ABCDEFABCDEFABCDEF.zip
header("Content-Disposition: attachment; filename= ". basename($_GET["fName"]));
This would make the server to name downloadable file as ABCDEFABCDEFABCDEF.zip
If you have saved your files without extension, then you might have a problem. If you have the orginal filename saved in database maybe you could add extra $_GET['orginalFilename'] to your links and use that to generate right filename with extension.
Also you are setting headers. They aren't being set correctly if you output anything before them. Here you print and finfo_file. You shouldn't do that.
I think you want something like this, but you have to figure out how to get right filename to the filename= part in header.
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename= ". basename($_GET["fName"]));
header("Content-Type: " . finfo_file($finfo, $_GET["fName"]));
finfo_close($finfo);
header("Content-Transfer-Encoding: binary");*/
// Read the file from disk
readfile($_GET["fName"]);