Skip to content
Advertisement

imagecreatefromweb causing FATAL error which cannot be caught

I have a simple block of code that when fed an invalid file should be able to provide some user feedback, but I am finding the call to imagecreatefromweb** simply stops all PHP processing with a “Fatal error: gd-webp cannot get webp info in ..” straight away.

I have tried to place this in a try catch but this doesn’t make a difference.

How do I catch this error?

$fn="c:/temp/some_image.jpg";
try {
     echo "<LI>Loading $fn";
     $imgRes = imagecreatefromwebp($fn); // Should really be "@imagecreatefromwebp($fn)"
     echo "<LI>Loaded ok";
}
catch (Exception $e) {
    echo "<LI>Exception ".$e->getMessage();
}
echo "<LI>Finished";

I am using PHP7.3.12 via Windows. (Note this code will work when fed a valid .webp file).

** (or imagecreatefromjpg or imagecreatefrompng, etc)

Advertisement

Answer

Use exif_imagetype() to ensure the file is in WEBP format:

<?php

    $fn="image.jpg";

    if (!file_exists($fn)) {
        echo 'File does not exists';
    } elseif (exif_imagetype($fn) === IMAGETYPE_WEBP) {
        $imgRes = imagecreatefromwebp($fn);
    } else {
        echo "Image is not in WEBP format";
    }

Note: use file_exists to ensure the file is really there

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement