According to a blog post from the (February 2010) of his error in the implementation of imagecreatefromjpeg , which should return false , but throws instead.
The solution is to check the file type of your image (I deleted the duplicate call to imagecreatefromjpeg because it is completely redundant: we already check the correct file type before and if the error occurs for any other reason, imagecreatefromjpeg will return false correctly):
function imagecreatefromjpeg_if_correct($file_tempname) { $file_dimensions = getimagesize($file_tempname); $file_type = strtolower($file_dimensions['mime']); if ($file_type == 'image/jpeg' || $file_type == 'image/pjpeg'){ $im = imagecreatefromjpeg($file_tempname); return $im; } return false; }
Then you can write your code as follows:
$img = imagecreatefrompng_if_correct("{$pathToImages}{$fname}"); if ($img == false) { // report some error } else { // enter all your other functions here, because everything is ok }
Of course, you can do the same for png if you want to open a png file (just like your code). In fact, usually you will check which file has its own file, and then call the correct function between the three (jpeg, png, gif).
source share