codeGEN
codeGEN

Reputation: 714

Image upload directory security

I have a php script that uploads images to a directory in the server. But I saw some comments mentioning that images should not be uploaded to the root directory for security concerns. I am not sure of the security vulnerabilities that could arise if I upload to the directory that I am currently uploading to. Here is the path where the images will be stored. htdocs/images/filenames.jpg.A screenshot of my directory is shown so that it would be clear

Please advice me on where to store the images in a secure manner.

Upvotes: 0

Views: 2036

Answers (1)

cyber-guard
cyber-guard

Reputation: 1846

There has been a lot of topics on the security of image uploads, but firstly it is permission of the directory 644 should do. Next you need to take care of the name, as suggested in the comments timestamp is fairly good way to go, however it must be combined with some randomly generated values (or use timestamp including milliseconds), however if you need to give the images a meaningful name, you must sanitize the user supplied name, filter out null bytes, directory traversals and other dangerous characters (I would whitelist and limit length of the image name, or randomly generate a string).

Rather than putting the image outside the web root, I prefer to use .htaccess with option php_flag engine off in it, to switch off any php execution in the directory. Also putting the images outside the web root makes them directly inaccessible, so you won't be able to use them in <img> tag, unless you use a PHP script to serve the image (which is a fairly secure method, if implemented correctly).

Lastly you want to check if a valid image is being uploaded, commonly the GD library is used, specifically the getimagesize, which will return image size only if a valid image is uploaded.

Also check this topic on security of image uploads.

Upvotes: 2

Related Questions