Assimilation
Assimilation

Reputation: 21

Validating image uploads with PHP

I have an image upload program setup that I made with PHP to allow the public to submit their images. I am having trouble finding a method to make sure the file is actually an image. I'm checking the file type, and also using getimagesize(), amongst other checks but if I rename a text file to become a JPG file my validation allows the file. How can I ensure this is actually an image? I don't want my boss to execute any infected files.

Upvotes: 2

Views: 1584

Answers (4)

user618788
user618788

Reputation:

Reproduce the uploaded image using gd. If the image isn't reproduced, it's not an image!

If this function returns false, then it's not a valid image. I haven't worked with any more than jpg, png and gif, so there might be some more image types out there that can fit into this function (bmp?)...

function checkFileType($filetype,$tmp_name)
{
    $return_val = false;
    switch($filetype){
        case 'image/jpg':
        case 'image/jpeg':
        case 'image/pjpeg':
            $return_val = @imagecreatefromjpeg($tmp_name);
        break;
        case 'image/gif':
            $return_val = @imagecreatefromgif($tmp_name);
        break;
        case 'image/png':
        case 'image/x-png':
            $return_val = @imagecreatefrompng($tmp_name);
        break;
    }
    return $return_val;
}

Upvotes: 0

plague
plague

Reputation: 1908

you can use Imagick's identifyImage() command.
if it gives you back image data its an image if it hands back an error or no image data then its not an image. there is a command line version of this tool you can use to: http://www.imagemagick.org/script/identify.php if you do not have php compiled with imagemagick

Upvotes: 1

lqez
lqez

Reputation: 3008

How about to use Exif module's exit-imagetype() function?

http://www.php.net/manual/en/function.exif-imagetype.php

<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
    echo 'The picture is not a gif';
}
?>

Upvotes: 0

genesis
genesis

Reputation: 50976

Check allowed extensions

.gif .jpg .jpeg .png should be allowed

Upvotes: 0

Related Questions