The most secured method to validate an image before to upload it

Hello all,

I am quite new in PHP so I am looking for some advices from PHP experienced programers about how to secure the upload of images.

Thank you

Well, #1 you cant validate something reliably before you upload it. It has to reach your server first :wink: (you can use javascript to try and validate, but what if the person has disabled javascript?)
#2 what security are you referring to here?

Thank you StarLion for your answer.
Maybe my statement was not so clear, sorry for this.

Manly, what i want to do is to implement a mechanism in PHP to upload some images.
The idea is that i don’t want somebody to upload, for example, PHP scripts which can be executed after and hack my website. This is the security i am talking about.

Hope i was more clear this time.

Thank you

You’ll have to upload the file first. When the file reaches $_SERVER[‘FILES’], then you can run a check against it, and delete it if you deem it unfit.


if ($_FILES["file"]["type"] != "image/jpeg") {
header(); //anywhere but here, file will be deleted
} else {

move_uploaded_file(); //where you want
}

I think you’ll find this question is already covered here

Thank you all for you answers, really helped me to understand the mechanism. Now, i will try to implement something and i will come back with a sample.

K. Wolfe’s code does only partial check and it still leaves your site vulnerable because $_FILES[“file”][“type”] is set by browsers and can be spoofed. This is good as the first check but then you should do at least two more checks:

  1. Use getimagesize() on the file, check if it was successful and also check the file type returned by index 2 - for jpeg’s it should be equal to constant IMAGETYPE_JPEG - then you can be sure the file is really a jpeg image.

  2. Check the file extension and allow only jpg/jpeg - someone could send you a .php file which is a php script embedded in a jpeg file container and who knows if he can find a vulnerability in the php interpreter to actually run the code if it ends with .php. Make sure that no undesirable file extensions land on your server.

  3. Lastly, you may run some final validations to check whether the image has proper dimensions, doesn’t exceed filesize limit, etc.