Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
930 views
in Technique[技术] by (71.8m points)

validation - How to check file types of uploaded files in PHP?

On the PHP website, the only real checking they suggest is using is_uploaded_file() or move_uploaded_file(), here. Of course you usually don't want user's uploading any type of file, for a variety of reasons.

Because of this, I have often used some "strict" mime type checking. Of course this is very flawed because often mime types are wrong and users can't upload their file. It is also very easy to fake and/or change. And along with all of that, each browser and OS deals with them differently.

Another method is to check the extension, which of course is even easier to change than mime type.

If you only want images, using something like getimagesize() will work.

What about other types of files? PDFs, Word documents or Excel files? Or even text only files?

Edit: If you don't have mime_content_type or Fileinfo and system("file -bi $uploadedfile") gives you the wrong file type, what other options are there?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Take a look at mime_content_type or Fileinfo. These are built-in PHP commands for determining the type of a file by looking at the contents of the file. Also check the comments on the above two pages, there are some other good suggestions.

Personally I've had good luck using something that's essentially system("file -bi $uploadedfile"), but I'm not sure if that's the best method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...