I have a PHP function below that is used for a command line tool for optimizing images, in the function below it is running ImageMagick on all files passed to it and getting the file extension.
I have only tested it on actual image files until tonight. I tested on a folder with images and other files mixed in.
The result is an error like this…
identify.exe: no decode delegate for this image format
`E:\Server\img\testfiles\archive.php' @ error/constitute.c/ReadImage/532.
Now I know it is kind of hard to filter the non-image files out when this function is specifically for the purpose of determining that value….But is there a better way that I can handle this situation, if a non-image file is passed through my program to this function, can I suppress the errors or avoid them from happening?
The function…
/**
* is_image
* @param mixed $file_path
* @static
* @access public
* @return void
*/
public static function is_image($file_path)
{
if (!file_exists($file_path)) {
throw new FileNotFoundException("File or path not found: " . $file_path);
}
$types = array("gif", "png", "gifgif", "jpg", "jpeg", "bmp");
//exec("/usr/bin/identify -quiet -format \"%m\" $file_path", $return, $error);
$imagemagick = self::$program_paths['imagemagick'] . '\identify';
exec($imagemagick . ' -quiet -format %m ' . $file_path, $return, $error);
$type = ($error === 0) ? mb_strtolower($return[0]) : "";
if ($error == 1) {
return false;
}
if (substr($type, 0, 6) === "gifgif") {
$type = "gifgif";
}
return in_array($type, $types);
}
Use the fileinfo functions to determine whether or not it’s an image first.