PHP File Upload Tutorial

      No Comments on PHP File Upload Tutorial

In this tutorial, I’m going to tell you how to upload file in PHP. A very useful aspect of PHP is its ability to manage file uploads to your server. Here are the two steps to do this:

Upload-File Form in HTML

Before you can use PHP to manage your uploads, you must first build an HTML form that lets users select a file to upload.  Have a look at the following HTML form for uploading files:


<form action="file_upload.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="uploaded_file" id=" uploaded_file" />
<br />
<input type="submit" name="submit" value="Submit" />


PHP Script to Upload File on Server

Now that we have the right HTML form we can begin to code the PHP script that is going to handle uploads. The “file_upload.php” file contains the code for uploading a file. When the file_upload.php file is executed, the uploaded file exists in a temporary storage area on the server. If the file is not moved to a different location it will be deleted!


if ($_FILES["uploaded_file"]["error"] > 0)
echo "Error: " . $_FILES["uploaded_file"]["error"] . "<br />";
echo "Upload: " . $_FILES["uploaded_file"]["name"] . "<br />";
echo "Type: " . $_FILES["uploaded_file"]["type"] . "<br />";
echo "Size: " . ($_FILES["uploaded_file"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["uploaded_file"]["tmp_name"];

if (file_exists("storage/" . $_FILES["uploaded_file"]["name"]))
echo $_FILES["uploaded_file"]["name"] . " already exists. ";
"upload/" . $_FILES["uploaded_file"]["name"]);
echo "Stored in: " . "storage/" . $_FILES["uploaded_file"]["name"];

By using the global PHP $_FILES array you can upload files from a client computer to the remote server and can save them on server. The first parameter is the form’s input name and the second index can be either “name”, “type”, “size”, “tmp_name” or “error”. Like this:

  • $_FILES[“uploaded_file”][“name”] – the name of the uploaded file
  • $_FILES[“uploaded_file”][“type”] – the type of the uploaded file
  • $_FILES[“uploaded_file”][“size”] – the size in bytes of the uploaded file
  • $_FILES[“uploaded_file”][“tmp_name”] – the name of the temporary copy of the file stored on the server. Using this temporary name you can move the file into permanent storage place.
  • $_FILES[“uploaded_file”][“error”] – the error code resulting from the file upload

Using “move_uploaded_file” function, you can move the file from temporary location to any specified permanent location at server.

In this way, you can upload the file in PHP from client computer to remote server and save it for future use. Cheers 🙂

Leave a Reply

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