PHP File Upload

What is it for?

Being able to upload a file through a web page has so many different applications from adding a picture to a member profile, uploading video to a video sharing site or sharing programme files across the web.

The basics are actually pretty easy to do but this tutorial comes with a Health Warning. You must protect or limit file uploads to your servers. Maybe create a user limit based on a log-in profile or make sure that allowed file sizes are kept small or your servers will be filled up with crap before you get a chance to clear it out!

How it works

For the purpose of this tutorial you will need to create a web page called upload.php and you will also need to create a folder in the root of your site (local or online) called 'uploads'. The uploads folder will store the uploaded files.

Now you have these two items we will start work on the upload.php page where all the magic will happen. First up you will need to create your upload form using HTML;

<form enctype="multipart/form-data" action="" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
Choose a file to upload: <input name="uploadedfile" type="file" />
<input type="submit" value="Upload File" name="submit" />
</form>

The form code will, of course, need to sit between your body tags on the page. Notice that the maximum upload size is set in the form itself and is written in bytes. 1000000 being 1MB. Also, for the purposes of this demo, I have set the for action to "" meaning that the form will be processed by PHP in this page.

The next thing we will want to do is to create a message to tell the user if the file has uploaded correctly. For this we will want to create a 'message' div to sit beneath the form;

<div id="message"><?php echo $message; ?></div>

Now for some PHP theory. Bear with me as this is important to understand if you want to complete various actions with the file after upload. To complete the file upload action and create some way of identifying the file afterwards we are going to make use of the super global $_Files array. This array can provide a PHP application with plenty of useful information about an uploaded file;

$_FILES["uploaded"]["error"]
$_FILES["uploaded"]["type"]
$_FILES["uploaded"]["name"]
$_FILES["uploaded"]["tmp_name"]
$_FILES["uploaded"]["size"]

Hopefully you can see how all of this information could be useful to you so it is worth knowing a little about it.

In the case of our upload.php page we are going to create a function that uploads the file from the users computer, stores it temporarily and then moves it to a folder called 'uploads' (which you should have already created). Here is the PHP code;

<?php
// Where the file is going to be placed
$target_path = "uploads/";

/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
//this checks if the form has been submitted.
$formsub = $_POST['submit'];

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
$message ="The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";

}
//this message triggers if the 'submit' button is pressed but there is no file to upload.
elseif($formsub){
$message ="There was an error uploading the file, please try again!";
}
?>

Let's go through that piece by piece. The 'target_path' variable allow us to append the folder path 'uploads/' to the file and so add the file to the 'uploads' folder. Next we take the uploaded file (NB: The name 'uploadedfile' is referenced from the HTML form we created earlier but this can be changed to suit your needs) and append that to the target path. This is done by using the ['name'] information from the $_FILES array, the 'basename' function which returns the filename from a path and using concatenation to put them together.

Now we use an if statement and the built in 'move_uploaded_file' function to place the file where we want it. The move_uploaded_file function asks for two things. Firstly the temporary file name and secondly where you'd like it to be moved to. It can be written like this;

move_uploaded_file(file,newloc)

The function returns TRUE or FALSE depending on success. You should spot that we are using $_FILES['tmp_name'] as the first part of the function and then moving that to the location in the 'target_path' variable we created earlier.

If the file move is a success the message fires and echos underneath our form in the HTML part of the page. Otherwise the second message will display on failure.

Conclusion

Put this script together in a whole page and then try uploading a file. If you have done everything correctly then your file will appear in your 'uploads' folder where you can use it for whatever purpose you like in your PHP application. Remember that this is very basic and you must protect your server from unwanted uploads which could be anything!

Advertisements If you would like to advertise on Corrosive Online then get in touch through my Contact Page for details.
Join The Mailing List
    If you have found anything on this site useful or entertaining or you have enjoyed one of my Online Web Design Lessons then I would love you to make a donation. Use the Paypal button below to make a donation.