Search code examples
phpfiletypesrestriction

PHP: $_FILES - Why should i restrict specific file types?


Today I was surfing around in the internet about how to upload files onto my webserver with a php formular, and somehow everybody only allows specific file typs (and restricts all others). For somebody who wants to upload a picture, it is not nice to see that the webpage does not except that file type. What´s the problem with other file types (for example, directly from w3schools.com: only JPG, JPEG, PNG & GIF are allowed).
Thankx in advance,
VicStudio


Solution

  • It is mainly for security reasons. Everything in $_FILES is coming from the user's browser, so if you do not have strict validation on what you accept, malicious users could upload files that are

    • too large — what if someone uploads a 10 GB image?
    • have a dangerous file type — what if someone uploads a .php file to your server? Game over.
    • have an invalid name — what if someone sets the file name to ../../../file.txt? When you save the file, it could end up in a different directory due to the ../.. in the path. This is called a Path Traversal vulnerability.

    When processing file uploads, you should validate all three of these against a whitelist. That is, have a list or range of values that you accept, and discard anything that does not fit those critera.