Page 1 of 1

Checking images on upload

Posted: Mon Dec 03, 2007 3:08 pm
by alex.barylski
What function is best to use if you are trying to determine whether a file is of type image or not???

Should I manually check the magic bytes in each file header? This is kind of a PITA so I was hoping for a GD function which would tell me whether a file was an image or not.

Likewise, how do "you" perform secure uploads when uploading arbitrary file types??? Obviously performing binary checks on each file type to confirm it's authenticity is just to much work.

Most importantly though I'd like to see a GD function which makes validating GIF/JPEG/PNG/etc. Really only those three are important. :)

Cheers :)

Posted: Mon Dec 03, 2007 3:33 pm
by vigge89
If you aren't happy with what getimagesize() offers you're stuck with checking the file headers if you want a accurate determination (as far as I know).

Posted: Mon Dec 03, 2007 3:36 pm
by alex.barylski
vigge89 wrote:If you aren't happy with what getimagesize() offers you're stuck with checking the file headers if you want a accurate determination (as far as I know).
I've had a look over the API several times now and it certainly looking that way. :(

I thought for sure I remembered a function like: imagetype() or similar which returned the type of image...shoot...

Ah well..

Posted: Mon Dec 03, 2007 5:23 pm
by s.dot

Code: Select all

if ($info = @getimagesize($_FILES['image']['tmp_name'])
{
    switch ($info[2])
    {
         case 1:
         //gif
         break;

         case 2:
         //jpg
         break;

         case 3:
         //png
         break;

         default:
         echo 'sorry dude, we only like gifs jpgs and pngs';
         break;
    }
} else
{
    echo 'sorry dude, upload an image';
}
That's usually what I do, in a sense.

Posted: Mon Dec 03, 2007 5:38 pm
by Christopher
I have had the problem that you have/want multiple checks for different file types coming from the library side, but from the programmer interface you just want to specify white/black lists -- so MIME types are best. Any system that, on the library side, converted disparate checks to MIME types would be preferable to make the final allow/deny check easy.

So I would like a combo of getmagesize() and image_type_to_mime_type(). Anyone want to write (or aggregate existing functions into) a library of functions that inspect different types of files (e.g. images, documents, audio/video, etc.) and return a MIME type?

Posted: Mon Dec 03, 2007 5:55 pm
by vigge89
I wouldn't hesitate having a go at making one if I didn't have as much to do as I got now =(
If anyone else would like to try I'd recommend visiting FILExt.com, they've got loads of references of file type headers and such worth looking up :)