When you allow users to upload files, your system may be at risk. Always restrict the file types that you allow. Don’t rely on a blacklist approach.

For example, a reasonable blacklist policy would seem to be Don’t allow the upload of .php files.

That’s a good policy until someone uploads a file named .htaccess. It’s not a PHP file so the blacklist won’t catch it. Placing this line in an .htaccess file and uploading it to a system only protected by a blacklist policy would open the door for the bad guys.

AddType application/x-httpd-php .php .htm


They can now upload any .htm file with PHP code in it and start poking around in your system.

For example.

<?php
echo system("locate config");
?>


Chances are good that the above code will give an attacker the name of every config file on the server. The possibilities for attacks are endless, all because of one unprotected upload form your server.

Be careful with file uploads and make sure you protect them with a whitelist policy instead. Make sure that the file that has been uploaded is of the type that you want to allow. There are several ways to do this, the easiest (and the easiest to defeat) is by checking the extension of the file uploaded. You can easily throw away any file that does not have the proper extension. However, that’s not the safest way to do it.

FOr a more secure check, look into the PECL extension, FileInfo. The documentation for it can be found here. FileInfo examins the contents of the file and tries to guess the content type based specific magic byte sequences. Using FileInfo as part of a strict whitelist policy is a much more secure way of allowing users to upload files to your system.