Search code examples
phplaravelintervention

Intervention Image Library - whenever a wrong image format is uploaded, I want to be able to catch it and send it to frontend in Laravel


I'm using the PHP intervention image library to upload images to my system. I'm using Laravel in the backend. When the format of the image is correct, it works fine but I'm not able to handle errors properly. I'm trying to test this feature by uploading .txt files expecting it to throw up an error and it is giving me an error in the backend. It is working fine until here.

development.ERROR: Unsupported image type text/plain. GD driver is only able to decode 
JPG, PNG, GIF, BMP or WebP files. 
{"exception":"[object(Intervention\\Image\\Exception\\NotReadableException(code: 0):
Unsupported image type text/plain. GD driver is only able to decode JPG, PNG, GIF, BMP or WebP files.

I'm trying to take this error and send it to the front end with a message to upload an image in the correct format but when I log the image array, it shows errors are 0.

Below is my code in Controller

Code for image creation in Laravel backend

$image = $this->request->file('image'); // getting the image from frontend
                
        \Log::info("image array is: ".print_r($image,true));

and here's the log error of the above log

output of Log message in Laravel

(
    [test:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 
    [originalName:Symfony\Component\HttpFoundation\File\UploadedFile:private] => iPad_useragents.txt
    [mimeType:Symfony\Component\HttpFoundation\File\UploadedFile:private] => text/plain
    [error:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 0
    [hashName:protected] => 
    [pathName:SplFileInfo:private] => /tmp/phpqPyk5F
    [fileName:SplFileInfo:private] => phpqPyk5F
)

In the output, we can see that the error is 0 but it is throwing an error when I upload the text file which is expected.

Could someone please help with how to handle this error i.e. whenever a wrong image format is uploaded, I want to be able to catch it and send it to the frontend in Laravel?


Solution

  • You can get the file mime type by calling $image->getMimeType();, and throw an error if its not an image type, before attempting to manipulate file as an image.