简体   繁体   中英

How to catch invalid image when using PHP imagecreatefromstring

i am using imagecreatefromstring and currently validate for proper image file format.

So a link of:

swqkdwfibqwfwf

Wont work, because its not a valid file type. But i have just discovered this:

sibdlsibiwbifw.png

Will send without an error from my validation. I get this error for an image link that doesnt return and image:

Warning: file_get_contents(etwteet.png): failed to open stream: No such file or directory in /var/www/clients/client2/web3/web/process/addnewbuild.php on line 141

Warning: imagecreatefromstring(): Empty string or invalid image in /var/www/clients/client2/web3/web/process/addnewbuild.php on line 141

Warning: imagejpeg() expects parameter 1 to be resource, boolean given in /var/www/clients/client2/web3/web/process/addnewbuild.php on line 143

Is there a way i can catch this error so i can stop the code processing and also notify the user?

Code used to get the URL:

$imagefile = image url;
$resource = imagecreatefromstring(file_get_contents($imagefile));

Thanks. Craig.

With all implementable validations, I believe it is finally required to capture error on imagecreatefromstring .

With an error handler...

Containing sytax available on PHP 5.3 or later.

set_error_handler(function ($no, $msg, $file, $line) {
    throw new ErrorException($msg, 0, $no, $file, $line);
});
try {
    $img = imagecreatefromstring(file_get_contents("..."));
} catch (Exception $e) {
    echo $e->getMessage();
}

With @ and error_get_last ...

if (!$img = @imagecreatefromstring(file_get_contents("..."))) {
    $e = error_get_last();
    die($e['message']);
}

Containing sytax available on PHP 5.4 or later.

if (!$img = @imagecreatefromstring(file_get_contents("..."))) {
    die(error_get_last()['message']);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM