PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, October 11, 2022

[FIXED] How to prevent having the "is not a valid image file" error when using GD function imagecreatefrom* in php?

 October 11, 2022     gd, image, imagecreatefrompng, php     No comments   

Issue

I am using imagecreatefromgif / imagecreatefromjpeg / imagecreatefromjpeg functions with uploaded images and sometimes get an error (e.g. Warning: imagecreatefromgif(): ... is not a valid GIF file) when the image is corrupted. I read lots of posts about this topic and couldn't find a "working" answer.

I did try some of the following to validate the image (as suggested on other posts) but none of them worked in ALL situations. If the image does not have the header info, the following works, but if the image has the header/mime type info and is corrupted, it doesn't work.

if( imagecreatefromjpeg($uploaded_image) !== false ) {
    // image is okay.
}

OR

try {
    $test = imagecreatefrompng($uploaded_image);
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

OR

using getimagesize($uploaded_image); // will return false or an error if image is not valid.

None of those situations worked with a corrupted image file that has the header info/mime type info.

I would like to prevent having those errors and if possible detect if the image is not corrupted and can be used without problems with any of the imagecreatefromgif / imagecreatefromjpeg / imagecreatefromjpeg functions. If corrupted, I would like to display an error message instead of running the funciton. I am looking for a solution in PHP.

Thank you for your help and suggestions.


Solution

You can try

$gd = @imagecreatefromstring(file_get_contents($file_path));    
    if ($gd === false) {
        throw new Exception ('Image is corrupted');
    }

It should work with most image formats known to gd. Also if you need specific error message you can use error_get_last().

@ will suppress error messages, and imagecreatefromstring tries to open known image formats. If this fails, $gd will have value 'false' and no error messages are thrown.

Edit:

Please not that in this example @ operator also will suprpess any errors from file_get_contents function.



Answered By - Mikk
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing