Securing File Uploads in PHP
File uploads are one of the most dangerous operations in the lifecycle of a web application. Keep them secure — otherwise, you are asking for trouble!
When it comes to the security of my applications, I always try to get paranoid. I try to put myself in the attacker’s shoes and wonder if my code can be used, in any way, to carry out an effective attack.
The most vulnerable part is, of course, the point of receipt of data from users. Usually, we have no doubts about the intentions of our users — we tend to trust them. We do not expect them to try to circumvent our security measures.
However, this does not free us from the obligation to apply data validation as strictly as possible. Sooner or later, even purely by accident, a shady visitor might come who will want to find gaps in your code and exploit it for his evil purposes, like stealing the data from your database!
One of the weak points is the code that receives files sent by our customers. Received files must be verified in terms of name, extension, type, and size.
If we only want to receive images (i.e. jpeg
and png
), we should not allow the transfer of other types of files (think exe
or php
) to your web server.