Is storing an image outside of the webserver root with a new name and extension (e.g. using move_uploaded_file($_FILES['userfile']['tmp_name'],'../uploads/'.date('U').'png') - not exactly this, obviously, since date('U') is not unique, and the uploading file would have to be run from the webserver root) and loading it with readfile() sufficient for securing an image upload form? If not, what kinds of attacks could get past this (e.g. running arbitrary php code, running javascript on the client etc...)?

  • In some cases, it depends on what processing you perform on the image. if any. Flaws have been found in libraries such as ImageMagick in the past, which would still apply if you used them to process vulnerable images. However, the risk would be reduced from a system whereby arbitrary files can be written to an accessible location.
    – Matthew
    Commented Feb 10, 2017 at 15:36

1 Answer 1


Yes, saving the files outside of the web root will reduce your attack surface for direct object references. I would also recommend doing the following:

  1. Validate the file when uploading - Check the mime-type of the file against a whitelist of valid image types. Also, check the mime-type of the bytes uploaded. Don't rely on what the browser told you the file was.
  2. Give the file a random name - You can append a timestamp to the end of the filename if you're concerned about uniqueness. If the user is able to upload a malicious file, a random name will make it harder for them to reference that file and have some webserver process execute it.
  3. Don't search for the file based on user-controlled input. This can leave you open to path traversal/more direct object reference (specifying another file, which they should not have access to.) issues.

The major attack vector that having a file upload can enable is local file inclusion aka. running arbitrary code on your sever. This could include running arbitrary php code and updating the javascript files. It could even result in the server itself being compromised depending on the permissions of the user account that your webserver is running under.

  • Regarding your last paragraph, does storing the uploaded images outside the web root reduce the possibility of this happening?
    – penalosa
    Commented Feb 10, 2017 at 18:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .