Uploading Files

Uploading a file in PHP has many great purposes, but it is also one of the biggest places to create a security risk. You absolutely have to make sure you do this correctly. If not, I will hunt you down and upload a script on your site that will make you wish you had. Not really, but you should build it like I might. When uploading a file, we will generally use a form to allow users to find the file they want to upload on their computer.

HTML File Upload Form


Choose a GIF file to upload:

Now, that is a cool form, but we don’t have any supporting server side code to tell it what to do. We need to craft a PHP file that will process the upload and check it to make sure it is the type of file that we want.

PHP Upload File


In our massively packed if statement example, you can see our server side checks. You must check to make sure the file’s attributes are exactly what you want. Here, we only check for file size and file type. We first check the file size by using $_FILES[“uploadedFile”][“size”], where “uploadedFile” is the name of our upload in the HTML form. The 10000 is the file size in bytes, which translates to about 10kb in this example. Next, we only want gif file types. So, we check the $_FILES[“uploadedFile”][“type”], or the file type, to see if it is a gif. Finally, our last check is to make sure no errors have come up by checking if $_FILES[“uploadedFile”][“error”] equals 0.

Now, we come to the heart of the uploading process. We set our folder path with the $filePath variable. Then, we reset it with the folder path and the actual file name with basename( $_FILES[‘uploadedFile’][‘name’]). Finally, we upload the file in an if statement to check for final errors with move_uploaded_file($_FILES[‘uploadedFile’][‘tmp_name’], $filePath). The move_uploaded_file function takes two parameters: the file name, which is $_FILES[‘uploadedFile’][‘tmp_name’], and the file path. This moves the file to a specific location so that we can view it later. See uploading is easy.

If you enjoyed this resource, support me by sharing this page with others.
Share on Facebook
Share on StumbleUpon
Digg this
Tweet about this on Twitter
Share on Reddit

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.