Upload & Save Image Files Using PHP Code Example in 2023

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

How to Upload and Save an Image File with PHP

  1. Confirm your PHP.ini settings are correct.
  2. Create an HTML form to upload the image file
  3. Add the file input element and a submit button in the form.
  4. The image is added to PHP’s TMP storage location on submission.
  5. Create a PHP script to transfer the image to your final destination.
  6. Update your database with the storage location using PHP code
  7. Return a 200 response back to the browser with the file reference.

PHP Code to Upload an Image File & Save it to Server

We can use a PHP script with an HTML form to upload files to the server. When we upload a file, it initially uploads into a temporary directory and is then relocated to the target location by a PHP script.

Here’s the simple php image upload script.

<?php
 
//If form submits successfully.
if($_SERVER["REQUEST_METHOD"] == "POST"){
    // If file uploads successfully
    if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){
        $allowedFileTypes = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png", "plain" => "text/plain", "html" => "text/html", "csv" => "text/csv");
        $filename = $_FILES["photo"]["name"];
        $filetype = $_FILES["photo"]["type"];
        $filesize = $_FILES["photo"]["size"];
   
        // Get file extension
        $extension = pathinfo($filename, PATHINFO_EXTENSION);
 
        //Check if file extension is valid.
        if(!array_key_exists($extension, $allowedFileTypes)) {
           throw new Error("Invalid file Format");
        }
   
        // Verify file size - 25MB max.
        $maxsize = 25 * 1024 * 1024;
        if($filesize > $maxsize){
            throw new Error("The File size is larger than the allowed limit.");
        }
   
        // Verify The MIME type of the file.
        if(in_array($filetype, $allowedFileTypes)){
            // Check whether file exists before uploading it
            if(file_exists("upload/" . $filename)){
                echo $filename . " is already exists.";
            }
            else {
                move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $filename);
                echo "Upload successful";
            }
        }
        //If not a valid MIME type
        else{
            throw new Error("Invalid file format");
        }
    }
    //If file fails to upload
    else{
        echo "Error: " . $_FILES["photo"]["error"];
    }
}
//If form fails to submit
else {
    throw new Error("Form submission failed");
}
?>

This article will demonstrate step-by-step how to upload files using PHP.

Step 1 | Configure the “php.ini” File Settings

To upload a file using PHP, first, we need to configure some key settings in the php.ini file. You can learn more about finding the PHP.ini file here.

PHP.ini | file_uploads

Open the php.ini file on your computer. Ensure the value of the file_uploads is On, as shown in the image below.

PHP File Upload Save
Enable File Upload

If the file_uploads value is off, then the uploading process will fail.

PHP.ini | upload_max_filesize

Next, we need to set the maximum file size in the php.ini file. If the maximum file size is less than the file we upload, we will get an error uploading the file. We can set desired maximum file size in the php.ini shown in the image below.

PHP File Upload Save
Change File Max Size

Step 2 | Create an HTML Form 

Let’s create an HTML form to upload a file using HTTP POST.

The following code creates an HTML form that allows users to upload a file.

HTML Form Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>File Upload Form</title>
</head>
<body>
    <form action="upload-manager.php" method="post" enctype="multipart/form-data">
        <h2>Upload File</h2>
        <label for="fileSelect">Filename:</label>
        <input type="file" name="photo" id="fileSelect">
        <input type="submit" name="submit" value="Upload">
        <p><strong>Note:</strong> Only .txt .jpg, .jpeg, .gif, .png formats are allowed to a max size of 15 MB.</p>
    </form>
</body>
</html>

Output

The above HTML code creates an HTML form, as shown in the image below.

PHP File Upload Save
HTML Form

The above HTML form has a method attribute set to post, and the enctype is to the multipart/form data.

Step 3 | Process the Uploaded File using PHP

Which PHP Function is used to Upload and Save Files?

PHP  move_uploaded_file(string $from, string $to): bool function uploads a file using PHP. This function moves the uploaded file to a new location. This function ensures the file is valid for uploading, and this check is very important.

In our example, we used this function like this.

PHP File Uploader Code Example

 move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $filename);

Which Array is used for PHP File Upload & Save?

To upload a file using PHP, we use the global $_FILES array.

Using this array, we can have the image file write to PHP web server. Afterwards, we upload files via the HTTP POST method. In our example, we used the $_FILES array like this.

This array receives the file from HTTP POST body.

$_FILES[“photo”]

With these basic queries resolved, let’s move on to the implementation.

Check if the Form Submits

First things first, the example needs to check if the form submits successfully, and for that, it uses IF/ELSE to ensure the script throws an error on form submission failure

//If form submits successfully.
if($_SERVER["REQUEST_METHOD"] == "POST"){
   // Rest of the logic goes here
}
//If form fails to submit
else {
    throw new Error("Form submission failed");
}

Check if File Uploads Successfully

The next logical step will be to check if the file has been uploaded successfully. So, the example uses another IF/ELSE to ensure that.

   // If file uploads successfully
   if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){
     //File upload logic goes here.
   }
 
   //If file fails to upload
   else{
   echo "Error: " . $_FILES["photo"]["error"];
   }

Check if File Extension is Valid

In this step, the example adds code to retrieve file information from the $_FILES array and uses an IF statement that would catch conditions when a file has an invalid extension.

$allowedFileTypes = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png", "plain" => "text/plain", "html" => "text/html", "csv" => "text/csv");
        $filename = $_FILES["photo"]["name"];
        $filetype = $_FILES["photo"]["type"];
        $filesize = $_FILES["photo"]["size"];
   
        // Get file extension
        $extension = pathinfo($filename, PATHINFO_EXTENSION);
 
        //Check if file extension is valid.
        if(!array_key_exists($extension, $allowedFileTypes)) {
           throw new Error("Invalid file Format");
        } 

Verify File Size

The next thing to check is whether the file size is within limits – 25MB in our case.

        // Verify file size - 25MB max.
        $maxsize = 25 * 1024 * 1024;
        if($filesize > $maxsize){
            throw new Error("The File size is larger than the allowed   limit.");
        }

Check the File MIME Type

Next, the example checks if the file MIME type (Media type) is correct. In the $allowedFileTypes array, the values are MIME types.

 // Verify The MIME type of the file.
if(in_array($filetype, $allowedFileTypes)){
 }
//If not a valid MIME type
else{
   throw new Error("Invalid file format");
 }

Check if File Already Exists

Finally, the example ensures if the file doesn’t exist already, and if that’s true, it uploads it to the temporary folder.

// Check whether file exists before uploading it
            if(file_exists("upload/" . $filename)){
                echo $filename . " is already exists.";
            }
            else {
                move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $filename);
                echo "Upload successful";
            }

Voila! Let’s put these pieces together in the next section.

PHP File Upload & Save – Full Example

<?php
 
//If form submits successfully.
if($_SERVER["REQUEST_METHOD"] == "POST"){
    // If file uploads successfully
    if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){
        $allowedFileTypes = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png", "plain" => "text/plain", "html" => "text/html", "csv" => "text/csv");
        $filename = $_FILES["photo"]["name"];
        $filetype = $_FILES["photo"]["type"];
        $filesize = $_FILES["photo"]["size"];
   
        // Get file extension
        $extension = pathinfo($filename, PATHINFO_EXTENSION);
 
        //Check if file extension is valid.
        if(!array_key_exists($extension, $allowedFileTypes)) {
           throw new Error("Invalid file Format");
        }
   
        // Verify file size - 25MB max.
        $maxsize = 25 * 1024 * 1024;
        if($filesize > $maxsize){
            throw new Error("The File size is larger than the allowed limit.");
        }
   
        // Verify The MIME type of the file.
        if(in_array($filetype, $allowedFileTypes)){
            // Check whether file exists before uploading it
            if(file_exists("upload/" . $filename)){
                echo $filename . " is already exists.";
            }
            else {
                move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $filename);
                echo "Upload successful";
            }
        }
        //If not a valid MIME type
        else{
            throw new Error("Invalid file format");
        }
    }
    //If file fails to upload
    else{
        echo "Error: " . $_FILES["photo"]["error"];
    }
}
//If form fails to submit
else {
    throw new Error("Form submission failed");
}
?>

Output

Upload a File
Upload a File

Resolving Common Errors

The File is too Large to Upload in PHP

If the file size we want to upload exceeds the maximum allowed size, then we get an error. To overcome this, we can simply increase the file size limit in the code and the php.ini file. You can find instructions on how to modify the PHP.ini file here.

By doing this, we can eliminate the error while uploading the file.

The Temporary Folder is Missing on PHP Upload

When the file is uploaded, initially, it is stored in a temporary directory on the server. We get the UPLOAD_ERR_NO_TEMP_DIR error when the temporary folder is missing. To resolve this error, we must ensure the temporary folder is writable on the server side. You will need to make sure it is defined and that it has permissions set to 755 or 777 depending on the use case.

A PHP Extension Stopped the File Upload

We get the UPLOAD_ERR_EXTENSION error if the upload is halted due to any extension. We can fix this error by figuring out which extension caused it, which can be hard if we upload multiple files with different extensions.

How to Limit the Image File Size in Our PHP Script

To limit the file, we need to perform a check in our PHP script. We can limit the file shown in the code below by performing a check by comparing the max file size and actual file size. The if condition checks if the uploading file size is greater than 25MB, then the file will not be uploaded.

// Verify file size - 25MB max.
        $maxsize = 25 * 1024 * 1024;
        if($filesize > $maxsize){
            throw new Error("The File size is larger than the allowed limit.");
        }

How to Limit Image File Types in PHP

The example uses an associative array to store the extensions and MIME types of the files that it expects to receive. You can extend that and add other extensions with their MIME types.

$allowedFileTypes = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png", "plain" => "text/plain", "html" => "text/html", "csv" => "text/csv");

The examples use a check to weed out incorrect MIME types.

// Get file extension
        $extension = pathinfo($filename, PATHINFO_EXTENSION);
 
        //Check if file extension is valid.
        if(!array_key_exists($extension, $allowedFileTypes)) {
           throw new Error("Invalid file Format");
        }

Where is the Temporary Directory & Tmp_name in PHP for the Image

The information inside the phpinfo.php page describes the temporary directory when a file is uploaded first as upload_temp_dir. The upload_max_filesize specifies the maximum size allowed for a file to be uploaded. We set these into a PHP configuration file called php.ini.

We must enable file writing permissions for the file’s temporary and final destinations. If either is disable, then the upload process will fail.

How to Store Uploaded Image Files in a Database using PHP

The database adds a layer of complexity to the example that we have seen. Generally, if you’re using a SQL database, you need to make insert queries to pass data to the database. Learn more about Database upload via PHP.

Wrap Up on Uploading Image Files with a PHP Script

This article demonstrates file upload and saving in PHP. The article uses an HTML file for uploading files and passing it to a PHP script using HTTP POST. The PHP script has many logical steps before it makes an attempt to upload the file.

I hope you’ve enjoyed the article. Stay tuned for more at FuelingPHP

Classes and Functions Mentioned

array_key_exists – (PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8) Checks if a key or index exists in the array.

move_uploaded_file – (PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8) Moves an uploaded file to a target location.

isset – (PHP 4, PHP 5, PHP 7, PHP 8) Checks if a variable in null or empty 

in_array – (PHP 4, PHP 5, PHP 7, PHP 8) Checks if a value exists in array.

pathinfo – (PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8) Returns a file’s path information

Get deeper with PHP

We have many fun articles related to PHP. You can explore these to learn more about PHP.

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.