I'm trying to detect if an image is an image when given a URL. To save an image from a url I used the following:
// create the image and save it
$imagefile = $URL;
$resource = imagecreatefromstring(file_get_contents($imagefile));
// X amount of quality is the last number
imagejpeg($resource, "images/covers/$imagepath.jpeg", 50);
imagedestroy($resource);
The $URL is simply an image link provided by the user.
I have tried the following:
$imagefile = $addBuildCover;
$resource = imagecreatefromstring(file_get_contents($imagefile));
if ($resource !== false) {
$return['imageGood'] = true;
} else {
$return['imageBad'] = true;
}
I have tried that code and i returns the correct JSON return of 'imageBad' but it's giving me an error before which is:
Warning: file_get_contents(ewffw.png): failed to open stream: No such file or directory in /var/www/clients/client2/web3/web/process/addnewbuild.php on line 116
Warning: imagecreatefromstring(): Empty string or invalid image in /var/www/clients/client2/web3/web/process/addnewbuild.php on line 116
How do I try I catch the URL fail but not actually have an error return like above?
imagecreatefromstring
will unfortunately warn if you pass it invalid data, so using it unnecessarily problematic.
You will have to shut it up with the error suppression operator @
:
$resource = @imagecreatefromstring(file_get_contents($imagefile));
Using this operator is something usually frowned upon, but this case is one which you really do have a legitimate use case.
This approach will also take care of the warning given from file_get_contents
if the file cannot be loaded. That function is not as badly behaved (there are ways to check with reasonable certainty if it will fail or not, e.g. is_readable
) so you could check with code instead of using @
, but since you need to suppress errors anyway and it makes no difference to you if the file read failed or not, just slapping a @
in front is IMHO fully warranted here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With