Friday, 15 March 2013

[PHP] How to Securing File Uploads


When letting a user upload a file, it is a very bad idea to not run any checks on that file. In the previous tutorial I showed you how to run a few cosmetic checks on it, but nothing that REALLY prevented someone from messing with your server.

Sure, stopping invalid mime types, excessive filesizes, and blank files could decrease the amount of spam by a lot, but it isn't enough to stop those who really know how to goof things up.



In this tutorial I will only discuss functions which are predefined in php's standard library for us; however, those are definitely not the only checks you're capable of executing. Firstly, do you remember the move_uploaded_file() and/or copy() functions? Well, how can you ensure that the file that's really being copied is the one that was selected by the file upload field?

If a user inputs something that has special meaning to the server, for instance, /../index.html as the file name, it could overwrite necessary elements to your website. PHP has a predefined function which helps us minimize this problem fairly well, it's called is_uploaded_file() and it takes one argument which is a string and is the file name you want to check for.

If you are running a version of php that is older than 4.0.3 then you may need to create or redefine the function to use yourself, because it is pretty useful. Here is a sample version which could be used for php versions less than 4.0.3.



Next, we can check file extensions as well. We can check file extensions to make sure the user didn't simply spoof the mimetype. Now, of course there are ways of spoofing both the mimetype and file extension, but I'm lucky enough to not have seen much of that in my day.

We could use a simply regular expression in order to check for file extensions we want to allow. File extensions can be found in the name element of the $_FILES superglobal. Let's say we wanted to allow users to upload pictures for a photo album, but we only wanted to allow .gif, .jpeg, and .png extensions. Below is an example of the code:



Note, if you are using the example for upload.php that was found in the other tutorial linked at the top of the page, you should delete lines 16-19 and place this code there instead.

With those steps, you can help secure your php file uploads, but those aren't the only precausions you can take to ensure safety for your server, website, and other users.

Resource Program Here

0 comments:

Post a Comment