Reputation: 2984
In php I can check if a uploaded file has proper type by extension, so 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 next step in my code I prepare a file for further processing. But what if someone changes a text_file.doc or javascript_file.js to samplefile.jpg before upload?
move_uploaded_file(($_FILES['photo1']['tmp_name']), "photos/1.jpg");
$source1 = imagecreatefromjpeg("../photos/source1.jpg");
Then user will see errors from imagecreatefromjpeg
step:
Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg: JPEG
library reports unrecoverable error: in...
How to skip a processing part if a file is not a graphic file and not display errors?
Upvotes: 5
Views: 3284
Reputation: 16304
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 function is not perfect, but it can cope with several image file formats.
There are several ways to omit the warnings in PHP. If an error like this can happen, it usually will happen. Either expect it in your code (usually preferrable, see my example with try...catch) or configurate your enviroment to your needs (p.e. omit warnings).
Upvotes: 3
Reputation: 1282
At first, you should edit php.ini to disable the output of warnings and error messages to the user, so these users don't see the error. At least for production systems this is recommended.
Then, you should be able to check the return value of the function. According to http://de.php.net/manual/en/function.imagecreatefromjpeg.php, it is supposed to return false if it cannot open the file you supplied.
Additionally, with exception handling ( see http://www.php.net/manual/en/language.exceptions.php ), you can catch and process error messages and warnings like the one you posted above.
Upvotes: 0
Reputation: 8101
As written on the documentation for file-uploads, it is stated that$_FILES['userfile']['type']
is
The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.
This means it is not checked on the php side, which you should do with mime_content_type and confirm its mime type.
Alternatively, you could use getimagesize to actually check if the file that has been uploaded has a imagesize, and if not, then its not an image.
Upvotes: 5