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
202 views
in Technique[技术] by (71.8m points)

PHP file upload: mime or extension based verification?

When I try to process file upload, should I run verification based on file MIME type or file-extension?

What are Pros & cons of these 2 ways of file validating?

And, Any other security issues should i be concerned of?

In these days I was relying on MIME type but the answer with most up-votes in this post

File upload issues in PHP says:

Never rely on the MIME type submitted by the browser!

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Okay, so to all the geniouses here yapping something about "SCREW EXTENSIONS, CHECK MIME! FILEINFO RLZ!", I've prepared some tutorial:

  1. Download this pretty php logo I drew
  2. View it. Pretty nice, isn't it?
  3. Rename it to whatever_you_like.php
  4. Put it through all your awesome mime type/whatever checkers
  5. Run it

In conclusion, you should NEVER EVER EVER rely on MIME type. You web server doesn't care about MIME type, it determines what to do by EXTENSION, the ultimately downvoted @Col. Shrapnel's answer is actually right. Any information provided to you by something checking MIME is absolutely irrelevant to your webserver when it comes to execution.

EDIT: the not-as-uncommon-code-as-you'd-want-it-to-be that opens a website to this type of attack:

<?php

$mimetype = mime_content_type($_FILES['file']['tmp_name']);
if(in_array($mimetype, array('image/jpeg', 'image/gif', 'image/png'))) {
   move_uploaded_file($_FILES['file']['tmp_name'], '/whatever/something/imagedir/' . $_FILES['file']['name']);
   echo 'OK';

} else {
    echo 'Upload a real image, jerk!';
}

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

...