Search code examples
phpimageexceptionintervention

PHP Intervention-image, avoid none image and exceptions to crash execution


I am building a filemanager. When I fetch all files, I make sure I have a thumbnail for the filemanager instead of loading big images into the view.

Problem

If the file is not an image, the intervention library will throw an exception. Of course, this is how it should be.I have a simple file extension check which is not a secure way of finding out it is an image or not. I will also get an exception if the source file does not exists. And maybe when other problems appear.

Image::make($source)
->resize(300, 300,  function ($constraint) {
    $constraint->aspectRatio();
    $constraint->upsize();
})
->save(Storage::disk()->path($target), $quality);

What I want to solve; The question

I don't want the exceptions to kill the whole process. This means that the filemanager crashes just because of wrong filetypes or any other problem.

Can I ignore the exception and just don't create a thumbnail and continue the PHP execution?


Solution

  • Correct answer in comments, by @arkascha

    All exceptions type (classes) are (if implemented correctly) derived from a common base class called "Exception". If you catch exceptions of a parent class all exceptions that are instantiations of that parents child class are caught too. (Sorry for the late response, had a flight to catch...)

    try { ... } catch (\Exception $e) { }

    Works because all exceptions extends to it