How to make sure that the downloaded file is jpg, gif or png?

In php, I can check if the downloaded file has the correct type by extension, so the code should look like this:

if ((($_FILES["photo1"]["type"] == "image/gif") || ($_FILES["photo1"]["type"] == "image/jpeg") || ($_FILES["photo1"]["type"] == "image/png")) && ($_FILES["photo1"]["size"] < 500000)) //also limiting size 

Then in the next step in my code I will prepare the file for further processing. But what if someone changes text_file.doc or javascript_file.js to samplefile.jpg before downloading?

 move_uploaded_file(($_FILES['photo1']['tmp_name']), "photos/1.jpg"); $source1 = imagecreatefromjpeg("../photos/source1.jpg"); 

Then the user will see errors from the imagecreatefromjpeg step:

 Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg: JPEG library reports unrecoverable error: in... 

How to skip part of the processing if the file is not a graphic file and does not display errors?

+4
source share
3 answers

I would use getimagesize and check for possible errors, something like this:

 try { $size = getimagesize("your_image_file"); echo 'image!'; } catch (Exception $e) { echo 'no known image format!'; } 

This GD feature is not perfect, but can handle several image file formats.

There are several ways to omit warnings in PHP. If such an error can occur, it usually will. Either expect it in your code (usually preferable, see My try ... catch example), or customize your environment to suit your needs (pe omit warnings).

+3
source

As written in the documentation for file-uploads , it is stated that $_FILES['userfile']['type'] is

The mime file type if the browser provided this information. An example is "image / gif". This mime type, however, is not tested on the PHP side and therefore does not take its value for granted.

This means that it is not checked on the php side, which you should do with mime_content_type and confirm its mime type.

Alternatively, you can use getimagesize to check if the file that was uploaded has an image, and if not, it is not an image.

+5
source

First you must edit php.ini to disable the display of warnings and error messages to the user, so these users do not see the error. At least for production systems, this is recommended.

Then you can check the return value of the function. According to http://de.php.net/manual/en/function.imagecreatefromjpeg.php , it should return false if it cannot open the file you specified.

In addition, with exception handling (see http://www.php.net/manual/en/language.exceptions.php ), you can catch and process error messages and warnings similar to the ones you specified above.

+1
source

Source: https://habr.com/ru/post/1382894/


All Articles