PHP File Upload

In this tutorial you'll learn how to upload a file to the remote web server with PHP.

Uploading Files with PHP

In this tutorial we will learn how to upload files on remote server using a Simple HTML form and PHP. You can upload any kind of file like images, videos, ZIP files, Microsoft Office documents, PDFs, as well as executables files and a wide range of other file types.

Step 1: Creating an HTML form to upload the file

The following example will create a simple HTML form that can be used to upload files.

Note: In addition to a file-select field the upload form must use the HTTP post method and must contain an enctype="multipart/form-data" attribute. This attribute ensures that the form data is encoded as mulitpart MIME data — which is required for uploading the large quantities of binary data such as image, audio, video, etc.

Step 2: Processing the uploaded file

Here's the complete code of our "upload-manager.php" file. It will store the uploaded file in a "upload" folder on permanent basis as well as implement some basic security check like file type and file size to ensure that users upload the correct file type and within the allowed limit.

Note: The above script prevents uploading a file with the same name as an existing file in the same folder. However, if you want to allow this just prepend the file name with a random string or timestamp, like $filename = time() . '_' . $_FILES["photo"]["name"];

You might be wondering what this code was all about. Well, let's go through each part of this example code one by one for a better understanding of this process.

Explanation of Code

Once the form is submitted information about the uploaded file can be accessed via PHP superglobal array called $_FILES. For example, our upload form contains a file select field called photo (i.e. name="photo"), if any user uploaded a file using this field, we can obtains its details like the name, type, size, temporary name or any error occurred while attempting the upload via the $_FILES["photo"] associative array, like this:

$_FILES["photo"]["name"] — This array value specifies the original name of the file, including the file extension. It doesn't include the file path.

$_FILES["photo"]["type"] — This array value specifies the MIME type of the file.

Tip: Once a file has been successfully uploaded, it is automatically stored in a temporary directory on the server. To store this file on a permanent basis, you need to move it from the temporary directory to a permanent location using the PHP's move_uploaded_file() function.