Tutorial: Uploading Files in PHP

August 15th, 2012 Leave a comment
Like the article?
Uploading Files in PHP

Once you have learned the basics of using forms in PHP, the next step is to begin working with and manipulating files. With PHP, you can allow users to upload files to the server and then use or store them. In this tutorial we will use a basic HTML form with a PHP script to upload files to your server.

To begin, we will create an HTML form in our upload.htm file.

          <title>PHP File Upload Example</title>
          <form enctype="multipart/form-data" method="post" action="upload.php">
     		<input type="file" name="fileName" /><br />
     		<input type="submit" value="Upload File" />

There are a couple of things to note about the HTML form:

  • Action – This attribute of the form is where we can assign the PHP file that we will write that will be handling the upload.
  • Enctype – This attribute allows us to set the way the browser uploads the data to the server.
  • We have an input type of “file” in the form. This is what gives us the Browse button and file box for the user to choose the file.

This is all we will need for the HTML. When uploading files with PHP, the file is uploaded to the server using the format stream you have specified and is put in a temporary directory. These files aren’t permanent, so in order to keep the file once it is uploaded our PHP script will need to move it to a new location.

Next, we will create the PHP script to handle the upload process.

Getting the Details of the Uploaded File

Once the user has chosen a file and clicked submit, you may want to use the information about the uploaded file or display the information to the user.

If you are wanting to retain or use information regarding the files that have been uploaded to your server, you can access the $_FILES array in PHP, which stores information about the file name, type, size and where it was temporarily stored on the server.

Beginning of upload.php

echo "<table border=\"1\">";
echo "<tr><td>Client Filename: </td>
<td>" . $_FILES["fileName"]["name"] . "</td></tr>";
echo "<tr><td>File Type: </td>
<td>" . $_FILES["fileName"]["type"] . "</td></tr>";
echo "<tr><td>File Size: </td>
<td>" . ($_FILES["fileName"]["size"] / 1024) . " Kb</td></tr>";
echo "<tr><td>Name of Temporary File: </td>
<td>" . $_FILES["fileName"]["tmp_name"] . "</td></tr>";
echo "</table>";

Here is the first part of our PHP script. We are creating a table in HTML to display the details of the file, using the $_FILES array. Notice that the name that we are using to access the particular file in the $_FILES array is the same name of the file upload input box from the form.

Also, note that we are dividing the file size by 1024 to get the size in Kb. The above code should produce an HTML table like this:

Client Filename:MyPic.jpg
File Type:image/jpeg
File Size:81.830078125 Kb
Name of Temporary File:C:\WINDOWS\TEMP\php48B2.tmp

Checking For Errors

One of the benefits of the $_FILES array is that it can be used to checks for problems during the upload process. When checking for errors, if there aren’t any then the value is zero (0). In the following code, we check this value with an IF statement and if it is greater than zero, you know there was an error and we can let the user know as well.

if ($_FILES["fileName"]["error"] > 0) {
     echo "Oh no! An error has occurred.";
     echo "Error Code: " . $_FILES["fileName"]["error"];

While this code is nice and will check for errors, you could also use a Switch statement, which would allow you to write more specific error messages back to the user, like this:

switch ($_FILES['fileName'] ['error']) {
  case 1:
    print '<p> The file is bigger than this server allows</p>';
  case 2:
    print '<p> The file is bigger than this form allows</p>';
  case 3:
    print '<p> Only part of the file was uploaded</p>';
  case 4:
    print '<p> No file was uploaded</p>';

Moving the File

As I mentioned before, if you want to store the file on the server for later use, you will need to move it to a new location or it will be deleted from the temp folder. This is the action we want to take if no errors occurred, so we will put this in the ELSE section of the error-check IF.

if ($_FILES["fileName"]["error"] > 0) {
  echo "Oh no! An error has occurred.";
  echo "Error Code: " . $_FILES["fileName"]["error"];
} else {
      "../uploads/" . $_FILES["fileName"]["name"]);

This bit of code uses the built-in function move_uploaded_file which takes in the temporary name of the file and the location you want the file moved to. This path can be an absolute location on your drive such as C:/php/uploads or a relative path like we are using in the example of ../uploads/.

Other Concerns

Opening your server to any file that your users want to upload is a risky idea. If you do not put any precautions in place you will have malicious users trying to put any file on your server and see if they can exploit this open door you have made. Since we usually don’t want our users uploading anything they want, or files of any size, we need to put some limitations in place.

Along with our error checking IF/ELSE statement, we will use another IF to determine if the file type and size fits our restrictions before allowing it to be uploaded. For this example we will only allow GIF, JPEG/JPG or PNG files.

Note that we cannot prevent the user from trying to upload any kind of file using this scripting method (but you could using other client-side techniques such as JavaScript) and the temp file will still be created. We will just prevent the user from actually getting the file uploaded and moved to the storage area.

if (($_FILES["fileName"]["type"] == "image/gif")
  || ($_FILES["fileName"]["type"] == "image/jpeg")
  || ($_FILES["fileName"]["type"] == "image/png" )) {
       //do the error checking if/else and upload if the check comes back OK
} else {
  echo "Files must be either JPEG, GIF, or PNG";

There are two ways you can prevent uploads based on size. You can limit it on the form so that the form will not process based on a maximum file size, or you can check in your script like we do for file type. You would also need to check that your server is configured to receive files up to the limit you are setting.

Form method:

We need to use a MAX_FILE_SIZE limit to the HTML form like this:

<input type="hidden" name="MAX_FILE_SIZE" value="10000" />

Script method:

if ($_FILES["fileName"]["size"] < 10000) {
  // this file is small enough to process
} else {
  echo "Files must be less than 10,000 kb";

Either way you choose, limiting the file size will prevent users from uploading huge files to your server which may use up your resources such as bandwidth and hard drive space or slowing your server down to the point it cannot be used by anyone else.

That’s it! Remember that by allowing users to upload files you are essentially opening a door to your server that could be exploited. Be sure that you are setting your file permissions correctly so that people cannot browse around the files that have been uploaded or that malicious code has not been uploaded or isn’t allowed to execute. Check out the attached source file for this example that has all of this code put together and is ready for you to install and use on your server.

Article Source Files

DescriptionNameSizeDownload method
Uploading Files With PHP Source Codeuploading_files_with_php.zip3KBHTTP
Help us spread the word!
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Delicious
  • DZone
  • Reddit
  • Sphinn
  • StumbleUpon
  • Google Plus
  • RSS
  • Email
  • Print
If you liked this article, consider enrolling in one of these related courses:
Don't miss another post! Receive updates via email!