PHP File Upload

The majority of people use PHP, a server-side language, for web development because of its ease of use and versatility. One of PHP’s most popular and often utilized features is file uploading. In this article, you will learn about PHP File Upload with the help of examples.

Understand about PHP File Upload

File upload is a basic feature for any web application or for website like most of the website have career page, where upload resume option available on that page etc. You can upload single and multiple files through PHP script and can upload files like images, videos, ZIP files, PDF files etc. We always create file input by multiple type:

Single File Upload

In HTML, input element with attribute type=”file” allows you to select one or more files and upload them to the server. Below shows the file input element:

<input type="file" id="uploadfile" name="uploadfile" />

Above input element always select only one file at a time to upload.

Multiple File Upload

Sometime we need to select more than one file to upload, then we use “multiple” attribute in input element. Below example show “multiple” attribute use with input element:

<input type="file" id="uploadfile" name="uploadfile" multiple />

Upload Specific Type of File

Sometimes, we need to upload certain type of files like only images, or only PDF etc. Then we can achieve this by use of accept attribute with input element, which accept files types in MIME format. Below example:

<input type="file" id="uploadfile" name="uploadfile" accept="image/png, image/jpeg" />

In above example, we have used image MIME types with comma separated, because we are using multi type files to upload like png and jpeg. We can add more file types with comma separated like bmp, gif etc.

In case of upload file, we use enctype” attribute in form element with multipart/form-data value. If we don’t use enctype attribute, then we can’t handle file upload on server side.

<form enctype="multipart/form-data" action="submit.php" method="post">
</form>

Also read about Form Handling In PHP

PHP File Upload Steps

There are some steps to upload file on server-side:

Step 1: Create HTML form

To handle file uploading, we need to create form with enctype attribute:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
    <title>File Upload Form Using PHP</title>
</head>
<body>
    <form action="submit.php" method="post" enctype="multipart/form-data">
        <h2>Upload File</h2>
        <label for="fileSelect">Filename:</label>
        <input type="file" name="uploadfile" id="uploadfileid" accept="image/png, image/jpg">
        <input type="submit" name="submit" value="Upload">
        <p><strong>Note:</strong> Upload only .jpg, .png file formats</p>
    </form>
</body>
</html>

Handling Form Submission Server-Side

In PHP, $_FILES (global variable) is used to display all the information of uploaded file. With the help of $_FILES, we can get uploaded file name, their type, their size, temp file name and errors.

Below is the list for responsible variable to check about uploaded file:

VariableDescription
$_FILES[‘filename’][‘name’]It always returns uploaded original file name.
$_FILES[‘filename’][‘type’]It always returns MIME type of the uploaded file like image/png, image/jpg etc.
$_FILES[‘filename’][‘size’]It always returns size of the uploaded file (in bytes).
$_FILES[‘filename’][‘tmp_name’]It always returns temporary file name of uploaded file which was stored on the server.
$_FILES[‘filename’][‘error’]It always returns error code associated with uploaded file.

When our form submit and file is uploaded successfully. It always stored in a temporary directory on the server. If we want to move uploaded file from temporary directory to our permanent directory, we use move_uploaded_file() function to move the file from the temporary directory to our permanent directory.

Syntax

bool move_uploaded_file ( string $filename , string $destination )

As you can see, move_uploaded_file() function takes two arguments:

  • $filename: It is is temporary file name, which is $_FILES[‘file’][‘tmp_name’].
  • $destination: It is the destination of your permanent directory name with filename.

move_uploaded_file()

This function always returns boolean value. If it return true means file move successfully and if it return false means file not moves successfully.

Below code of “submit.php” file, which shows use of move_uploaded_file() with some basic file validation like uploaded file types and uploaded file size to ensure that users upload the correct file and within the allowed limit.

submit.php

<?php

if(!isset($_FILES["uploadfile"]) && !empty($_FILES["uploadfile"]))
{
    if($_FILES["uploadfile"]["error"] == 0)
	{
        $allowedtype = array("jpg" => "image/jpg", "png" => "image/png");
        $uploadfilename = $_FILES["uploadfile"]["name"];
        $uploadfiletype = $_FILES["uploadfile"]["type"];
        $uploadfilesize = $_FILES["uploadfile"]["size"];
    
        $ext = pathinfo($uploadfilename, PATHINFO_EXTENSION);
        if(!array_key_exists($ext, $allowedtype)) 
			die("Error: Please select a valid file format.");
    
        $filemaxsize = 5 * 1024 * 1024;
        if($uploadfilesize > $filemaxsize) 
			die("Error: File size is larger than the allowed limit.");
    
        if(in_array($uploadfiletype, $allowedtype))
		{            
            if(file_exists("upload/" . $uploadfilename))
			{
                echo $uploadfilename . " is already exists.";
            } 
			else
			{
                $result = move_uploaded_file($_FILES["uploadfile"]["tmp_name"], "upload/" . $uploadfilename);
				
				if($result)
				{
					echo "Your file was uploaded successfully.";
				}
				else
				{
					echo "File not uploaded successfully";
				}				
            } 
        } 
		else
		{
            echo "File not uploaded successfully."; 
        }
    } 
	else
	{
        echo "Error: " . $_FILES["uploadfile"]["error"];
    }
}
?>

PHP file uploading is a simple procedure, but it needs close attention to detail to guarantee security and dependability. Your online application can have a safe and effective file upload system if you adhere to standard practices and use strong validation. PHP gives you the tools you need to accomplish operations like simple file uploads and more complicated scenarios requiring numerous files or database storage.

Categorized in: