deniz
deniz

Reputation: 189

Imagecreatefromjpeg With Faulty File

im writing an script that resize and crops the uploaded images.

all valid files are ok... but some of my visitors are trying to upload non-valid ones.. for example the file extension is jpg, but in fact its a tiff file .. the uploading file's extension looks gif, but in its exif details writes 'its a jpg'.. etc..

As you can imagine, imagecreatefromXX() functions are all giving error in that case (its not a valid jpg etc)..

do you have any idea, how may i solve this problem?

how must i modify my recent codes?

switch($type) {
    case 'gif':
    $img = imagecreatefromgif($source);
    break;
    case 'jpg':
    case 'JPEG':
    case 'jpeg':
    $img = imagecreatefromjpeg($source);
    break;
    case 'png':
    $img = imagecreatefrompng($source);
    break;  
}

Upvotes: 1

Views: 375

Answers (1)

GeminiDomino
GeminiDomino

Reputation: 451

Your best bet would probably be to modify the code that sets $type, rather than the code you've shared (though John Conde's suggestion to have a default case is a good one), and use something like exif_imagetype (which your question suggests might already be in play) to determine the type, rather than trusting the extension (which you may even want to change to the appropriate type when writing the file): the extension is user-supplied data, and as such, the least likely to be accurate and/or useful.

e.g.

$type = exif_imagetype($source);
switch ($type){
     case IMAGETYPE_GIF:
             $img = imagecreatefromgif($source);
             break;
     case IMAGETYPE_JPG:
             $img = imagecreatefromjpeg($source);
             break;
     case IMAGETYPE_PNG:
         ... etc ...

     default:
         //Fail Gracefully
 }

Upvotes: 1

Related Questions