سؤال

I am trying to serve files uploaded by users with PHP.

While it would be easy to just point to the file, there seems to be agreement that you should not point directly to a directory on the site as this creates a security risk...If someone can get a malicious file past barriers onto site, it is then a cinch for them to execute it if they know where it sits on server. Instead, recommendation is to put files in a folder outside the tree structure of the site, store name in database as something other than original name, along with a file path to the hidden directory, and serve it using a PHP file that reads and displays. I am able to do all this and display gibberish using:

// get mime type somehow//

header("Content-type:".$mimetype);
readfile($totalfilepath);

The problem is how to get the correct mime type so it displays a nice file instead of gibberish.

If you have 5.3, you can use finfo as follows:

$finfo = finfo_open(FILEINFO_MIME_TYPE);
header("Content-Type: ".finfo_file($finfo, 'files/'.$file));
finfo_close($finfo);
readfile('files/'.$file);  

Unfortunately, finfo doesn't work in 5.2 There is also a function called

mime_content_type

however, it is deprecated as of 4.xx and is not on my server in any case. From what I have read, there does not seem to be a reliable way to get the mime type before 5.3. I don't want to upgrade to 5.3 as it will require upgrading of a very large site.

Note: the files that are allowed for upload include .jpg, .gif, .png, .pdf files, the major office files, doc, docs, xls, xlx, etc. and txt files.

Also, I would be open to forcing a download of the files instead of displaying them in browser, however, first choice is displaying in browser.

هل كانت مفيدة؟

المحلول

The required information is returned by the getimagesize() function. How to get this information is explained in the PHP manual. The image_type_to_mime_type() function can be helpful, too. Examples are provided in the online manual too.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top