• Tutorial List

PHP File Uploading

Last updated Apr 04, 2020

How to upload files using PHP?

Using PHP, you can easily upload any types of files to the server such as images, PDF files, videos, etc.

๐Ÿ‘‰ Configuration of the “php.ini” file

First, open your “php.ini” file and make sure that file_uploads enabled. Otherwise, you will get errors when you try to upload files.

Enabling file uploads

As well as inside the php.ini file, you can increase upload_max_filesize according to your needs.

In the following image, the upload_max_filesize=2M, which means you can’t upload those files whose size is over 2MB.

php.ini upload_max_filesize

๐Ÿ‘‰ Creating the HTML Form

The following HTML form will be used to upload files –

<!DOCTYPE html>
<html>
<body>

    <form action="./index.php" method="POST" enctype="multipart/form-data">
        <label for="myFile"><b>Select file to upload:</b></label><br>
        <input type="file" name="targetFile" id="myFile">
        <input type="submit" name="submitUpload" value="Upload">
    </form>

</body>
</html>
  • action=”index.php”
    • When the form is submitted, the form data is sent to the index.php which is the current page.
  • method=”POST”
    • Sending the form data to index.php via the POST Method/Request.
  • enctype=”multipart/form-data”
    • It defines the data encoding type. The enctype MUST be specified as the above.
  • name=”targetFile”
    • We can access the requested file via the targetFile name. You can change this name according to your choice. Like – name="going_to_upload"

๐Ÿ‘‰ Writing codes for uploading files

The HTML form sends the form data to index.php, that’s why we have to write the uploading code into the index.php.

<?php
    // IF THE FORM IS SUBMITTED & FOUND THE REQUESTED FILE -
    if(isset($_POST['submitUpload']) && isset($_FILES['targetFile'])){

        //FILE UPLOADING CODE GOES HERE
        
        echo "<pre>";

        // SHOWING THE DETAILS OF THE FILE GOING TO BE UPLOADED
        var_dump($_FILES['targetFile']);

        echo "</pre>";
        
        //It will stop the execution of the following code.
        exit;

    }
?>
<!DOCTYPE html>
<html>
<body>

    <form action="./index.php" method="POST" enctype="multipart/form-data">
        <label for="myFile"><b>Select file to upload:</b></label><br>
        <input type="file" name="targetFile" id="myFile">
        <input type="submit" name="submitUpload" value="Upload">
    </form>

</body>
</html>
  • isset() function
    • The isset() function checks the availability of a variable.
  • $_POST
    • The $_POST is a superglobal variable which is used to access form data after submitting an HTML form with method=”POST”.
  • $_FILES
    • The $_FILES is another superglobal variable that is used to access the request files which are going to be uploaded after submitting an HTML form with method=”POST” & enctype=”multipart/form-data”.
    • This variable contains an associative array, which contains the information of the going to be uploaded file.
  • exit;
    • The exit function stops the execution of the script when you call it.

Attempting to upload a file –

Browser Output
array(5) {
  ["name"]=>
  string(13) "mountains.png"
  ["type"]=>
  string(9) "image/png"
  ["tmp_name"]=>
  string(24) "C:\xampp\tmp\phpBFA2.tmp"
  ["error"]=>
  int(0)
  ["size"]=>
  int(565858)
}

Simple code for uploading files

First, create a folder called ๐Ÿ“uploads inside your app root. The uploads folder is the folder where the uploaded file will be stored.

PHP File upload folder structure
<?php
    // IF THE FORM IS SUBMITTED & FOUND THE REQUESTED FILE -
    if(isset($_POST['submitUpload']) && isset($_FILES['targetFile'])){

        // THIS IS THE PATH OF THE FOLDER WHERE THE UPLOADED FILES WILL BE STORED.
       $upload_dir = './uploads/';

       /*
       Adding the name you want to save the file to the server

       in the following, adding the original name of the file.
       './uploads/CURRENT_FILE_NAME'

       EXAMPLE - './uploads/my-image.png'
       */
       $targetFile = $upload_dir.$_FILES['targetFile']['name'];


       /*
        When a request is sent to a server to upload files,
        first, the file or files are uploaded to the server temporary folder
        and after successfully uploading or canceling upload,
        the uploaded files will be automatically removed from the temporary folder.
        
        The following $tmpName is the path of the temporary file.
       */
       $tmpName = $_FILES["targetFile"]["tmp_name"];

       // UPLOADING THE FILE -
       $is_uploaded = move_uploaded_file($tmpName, $targetFile);

        // CHECKING WHETHER THE FILE HAS BEEN UPLOADED OR NOT
       if($is_uploaded){
            echo "The file uploaded successfully";
       }
       else{
            echo "The file not uploaded.";
       }
        
        //It will stop the execution of the following code.
        exit;

    }
?>
<!DOCTYPE html>
<html>
<body>

    <form action="./index.php" method="POST" enctype="multipart/form-data">
        <label for="myFile"><b>Select file to upload:</b></label><br>
        <input type="file" name="targetFile" id="myFile">
        <input type="submit" name="submitUpload" value="Upload">
    </form>

</body>
</html>
  • $upload_dir
    • This is the path of the folder where the uploaded files will be stored.
  • $tmpName
    • The $tmpName is the path of the temporary file.
  • move_uploaded_file()
    • The PHP move_uploaded_file() function is used to upload files to a server.
    • This function takes two parameters –
      1. Temporary file name.
      2. Destination of the file
    • This function returns true on upload success.

Trying to upload a file –

Browser Output
The file uploaded successfully

๐Ÿ“ If you want to upload the same file again, you have to change the file name, otherwise, the new file will replace the old file.


How to handle file upload errors?

Every file array contains the error key, and the error key contains an integer value and each integer value indicates a special message.

<?php
  
  $error_int = $_FILES['targetFile']['error'];

?>
  • ($error_int === 0)
    • There is no error, the file uploaded with success.
  • ($error_int === 1)
    • The uploaded file exceeds the upload_max_filesize.
  • ($error_int === 2)
    • The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
  • ($error_int === 3)
    • The uploaded file was only partially uploaded.
  • ($error_int === 4)
    • No file was uploaded.
  • ($error_int === 6)
    • Missing a temporary folder. Introduced in PHP 5.0.3.
  • ($error_int === 7)
    • Failed to write file to disk. Introduced in PHP 5.1.0.
  • ($error_int === 8)
    • A PHP extension stopped the file upload.

Example:

<?php
    if(isset($_POST['submitUpload']) && isset($_FILES['targetFile'])){

        // FILE ERROR
       $error_int = $_FILES['targetFile']['error'];

       $upload_dir = './uploads/';

       $targetFile = $upload_dir.$_FILES['targetFile']['name'];

       $tmpName = $_FILES["targetFile"]["tmp_name"];
		
      //CHECKING THE UPLOAD LIMIT
       if($error_int === 1){
           echo "File is too large | The uploaded file exceeds the upload_max_filesize.";
       }
       else{

            $is_uploaded = move_uploaded_file($tmpName, $targetFile);

            if($is_uploaded){
                echo "The file uploaded successfully";
            }
            else{
                echo "The file not uploaded.";
            }

       }

       exit;

    }
?>
<!DOCTYPE html>
<html>
<body>

    <form action="./index.php" method="POST" enctype="multipart/form-data">
        <label for="myFile"><b>Select file to upload:</b></label><br>
        <input type="file" name="targetFile" id="myFile">
        <input type="submit" name="submitUpload" value="Upload">
    </form>

</body>
</html>

How to limit file upload size in PHP?

Now we will see how to set the upload size limit so that a user can upload only limited size files.

Every file array also has a “size” key, and the “size” key contains the file size.

<?php
  
	$fileSize = $_FILES['targetFile']['size'];

?>

In the following example, only those files are allowed to upload which size is not over 1MB.

<?php
    if(isset($_POST['submitUpload']) && isset($_FILES['targetFile'])){

        $error_int = $_FILES['targetFile']['error'];

        // THE FILE SIZE
        $fileSize = $_FILES['targetFile']['size'];

        $upload_dir = './uploads/';

        $targetFile = $upload_dir.$_FILES['targetFile']['name'];

        $tmpName = $_FILES["targetFile"]["tmp_name"];

        if($error_int === 1){
            echo "File is too large | The uploaded file exceeds the upload_max_filesize.";
        }
        // 1048576 = 1MB
        // Only below 1MB files are allowed to upload
        elseif($fileSize > 1048576){
            echo "The file size is over 1MB, that's why this file is not allowed to upload.";
        }
        else{

            $is_uploaded = move_uploaded_file($tmpName, $targetFile);

            if($is_uploaded){
                echo "The file uploaded successfully";
            }
            else{
                echo "The file not uploaded.";
            }

        }

        exit;
    }
?>
<!DOCTYPE html>
<html>
<body>

    <form action="./index.php" method="POST" enctype="multipart/form-data">
        <label for="myFile"><b>Select file to upload:</b></label><br>
        <input type="file" name="targetFile" id="myFile">
        <input type="submit" name="submitUpload" value="Upload">
    </form>

</body>
</html>

๐Ÿ“ If the uploaded file exceeds the upload_max_filesize, it will return the file size 0, that’s why you have to check the file size after checking the upload_max_filesize.


How to check a file already uploaded or not?

When you try to upload a file, and if a file already exists in the ๐Ÿ“uploads folder with the same name and extension, then the new file will replace the old file.

So, If you don’t want to replace the old file, you have to check the file existence before uploading.

The file_exists() function is used to check a file existence.

<?php
  if(file_exists($targetFile)){
      echo "File already exists. Please change the file name, and try again.";
  }
?>
<?php
    if(isset($_POST['submitUpload']) && isset($_FILES['targetFile'])){

        $error_int = $_FILES['targetFile']['error'];

        $fileSize = $_FILES['targetFile']['size'];

        $upload_dir = './uploads/';

        $targetFile = $upload_dir.$_FILES['targetFile']['name'];

        $tmpName = $_FILES["targetFile"]["tmp_name"];

        // Checking the file existence
        if(file_exists($targetFile)){
            echo "File already exists. Please change the file name, and try again.";
        }
        elseif($error_int === 1){
            echo "File is too large | The uploaded file exceeds the upload_max_filesize.";
        }
        elseif($fileSize > 1048576){
            echo "The file size is over 1MB, that's why this file is not allowed to upload.";
        }
        else{

            $is_uploaded = move_uploaded_file($tmpName, $targetFile);

            if($is_uploaded){
                echo "The file uploaded successfully";
            }
            else{
                echo "The file not uploaded.";
            }

        }

        exit;
    }
?>
<!DOCTYPE html>
<html>
<body>

    <form action="./index.php" method="POST" enctype="multipart/form-data">
        <label for="myFile"><b>Select file to upload:</b></label><br>
        <input type="file" name="targetFile" id="myFile">
        <input type="submit" name="submitUpload" value="Upload">
    </form>

</body>
</html>

How to rename a file before uploading?

In the following example, we will rename those files that already exist in the ๐Ÿ“uploads folder with the same name and extension. So that the new file cannot replace the old file.

<?php
    if(isset($_POST['submitUpload']) && isset($_FILES['targetFile'])){

        $error_int = $_FILES['targetFile']['error'];

        $fileSize = $_FILES['targetFile']['size'];

        $upload_dir = './uploads/';

        $targetFile = $upload_dir.$_FILES['targetFile']['name'];

        //GET THE PATH INFORMATION
        $path_info = pathinfo($_FILES["targetFile"]["name"]);

        $tmpName = $_FILES["targetFile"]["tmp_name"];

        if($error_int === 1){
            echo "File is too large | The uploaded file exceeds the upload_max_filesize.";
        }
        // CHECKING EMPTY FILE
        elseif($error_int === 4){
            header('Location: index.php');
            exit;
        }
        elseif($fileSize > 1048576){
            echo "The file size is over 1MB, that's why this file is not allowed to upload.";
        }
        else{

            // IF THE FILE EXISTS, THEN RENAME IT
            /*
                if example.txt already exists
                    then-> example-1.txt
                if example-1.txt already exists
                    then-> example-2.txt
                .....It will continue 3,4,5.....
            */
            $number = 1;
            while(file_exists($targetFile)){
                $targetFile = $upload_dir.$path_info['filename'].'-'.$number.'.'.$path_info['extension'];
                $number++;
            }

            $is_uploaded = move_uploaded_file($tmpName, $targetFile);

            if($is_uploaded){
                echo "The file uploaded successfully";
            }
            else{
                echo "The file not uploaded.";
            }

        }

        exit;
    }
?>
<!DOCTYPE html>
<html>
<body>

    <form action="./index.php" method="POST" enctype="multipart/form-data">
        <label for="myFile"><b>Select file to upload:</b></label><br>
        <input type="file" name="targetFile" id="myFile">
        <input type="submit" name="submitUpload" value="Upload">
    </form>

</body>
</html>

How to upload only specific types of files?

In the following example, we will be allowed to upload only images. Such as – ['png','jpg','jpeg','gif']

<?php
    if(isset($_POST['submitUpload']) && isset($_FILES['targetFile'])){

        $error_int = $_FILES['targetFile']['error'];

        $fileSize = $_FILES['targetFile']['size'];

        $upload_dir = './uploads/';

        $targetFile = $upload_dir.$_FILES['targetFile']['name'];

        //GET THE PATH INFORMATION
        $path_info = pathinfo($_FILES["targetFile"]["name"]);

        $tmpName = $_FILES["targetFile"]["tmp_name"];

        // THE ARRAY OF FILE TYPES WHICH YOU WANT OT ALLOW TO UPLOAD
        $fileType = ['png','jpg','jpeg','gif'];

        if($error_int === 1){
            echo "File is too large | The uploaded file exceeds the upload_max_filesize.";
        }
        // IF EMPTY FILE
        elseif($error_int === 4){
            header('Location: index.php');
            exit;
        }
        elseif($fileSize > 1048576){
            echo "The file size is over 1MB, that's why this file is not allowed to upload.";
        }
        // IF THE FILE EXTENSION IS NOT IN ARRAY
        elseif(!in_array($path_info['extension'],$fileType)){
            echo "Please choose an Image file.";
        }
        else{

            $number = 1;
            while(file_exists($targetFile)){
                $targetFile = $upload_dir.$path_info['filename'].'-'.$number.'.'.$path_info['extension'];
                $number++;
            }

            $is_uploaded = move_uploaded_file($tmpName, $targetFile);

            if($is_uploaded){
                echo "The file uploaded successfully";
            }
            else{
                echo "The file not uploaded.";
            }

        }

        exit;
    }
?>
<!DOCTYPE html>
<html>
<body>

    <form action="./index.php" method="POST" enctype="multipart/form-data">
        <label for="myFile"><b>Select file to upload:</b></label><br>
        <input type="file" name="targetFile" id="myFile">
        <input type="submit" name="submitUpload" value="Upload">
    </form>

</body>
</html>

Upload images and store the name of the images into the database

In the following example, we will see how to upload images and store the name of the images into the database using PHP.

Database Name โ€“ upload_image
Table Name โ€“ images

Use the following SQL code to create the images table and the structure of the images table –

CREATE TABLE `images` (
  `image_id` int(11) NOT NULL,
  `image_name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
ALTER TABLE `images`
  ADD PRIMARY KEY (`image_id`);
ALTER TABLE `images`
  MODIFY `image_id` int(11) NOT NULL AUTO_INCREMENT;
<?php

    // DATABASE CONNECTION
    $db_conn = mysqli_connect("localhost","root","","upload_image");

    // CHECKING THE DATABASE CONNECTION
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL Database: " . mysqli_connect_error();
        exit;
    }

    // FETCH ALL IMAGES FROM DATBASE
    $all_images = mysqli_query($db_conn,"SELECT * FROM `images`");
    

    if(isset($_POST['submitUpload']) && isset($_FILES['targetFile'])){

        $error_int = $_FILES['targetFile']['error'];

        $fileSize = $_FILES['targetFile']['size'];

        $upload_dir = './uploads/';

        $targetFile = $upload_dir.$_FILES['targetFile']['name'];

        $path_info = pathinfo($_FILES["targetFile"]["name"]);

        $tmpName = $_FILES["targetFile"]["tmp_name"];

        $fileType = ['png','jpg','jpeg','gif'];

        if($error_int === 1){
            echo "File is too large | The uploaded file exceeds the upload_max_filesize.";
        }
      	// if $_FILES IS EMPTY
        elseif($error_int === 4){
            header('Location: index.php');
            exit;
        }
        elseif($fileSize > 1048576){
            echo "The file size is over 1MB, that's why this file is not allowed to upload.";
        }
        elseif(!in_array($path_info['extension'],$fileType)){
            echo "Please choose an Image file.";
        }
        else{

            $number = 1;
            while(file_exists($targetFile)){
                $targetFile = $upload_dir.$path_info['filename'].'-'.$number.'.'.$path_info['extension'];
                $number++;
            }

            $is_uploaded = move_uploaded_file($tmpName, $targetFile);

            if($is_uploaded){

                $file_name = basename($targetFile);

                // INSERT STATEMENT
                $image_name_insert_stmt = mysqli_prepare($db_conn, "INSERT INTO `images` (image_name) VALUES (?)");
                mysqli_stmt_bind_param($image_name_insert_stmt, "s", $file_name);

                // CHECKING, IF THE FILE NAME SAVED
                if(mysqli_stmt_execute($image_name_insert_stmt)){
                    header('Location: index.php');
                    exit;
                }
                else{
                    echo "Failed to save the file name into the Database.";
                }

                echo "The file uploaded successfully";
            }
            else{
                echo "The file not uploaded.";
            }

        }

        exit;
    }
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Upload Images</title>
        <style>
            .all_images{
                display:flex;
                flex-wrap:wrap;
            }
            .image-wrapper{
                width:150px;
                border:1px solid #dedede;
                flex:1 1 auto;
                margin:5px;
                padding:3px;
                display:flex;
            }
            .image-wrapper img{
                width:100%;
                display:block;
            }

        </style>
    </head>
<body>

    <form action="./index.php" method="POST" enctype="multipart/form-data">
        <label for="myFile"><b>Select file to upload:</b></label><br>
        <input type="file" name="targetFile" id="myFile">
        <input type="submit" name="submitUpload" value="Upload">
    </form>

    <hr/>
    <h3>All images</h3>

    <div class="all_images">
        <?php
        if(mysqli_num_rows($all_images) > 0){

            while($row = mysqli_fetch_assoc($all_images)){

                echo '<div class="image-wrapper">
                <img src="uploads/'.$row['image_name'].'">
            </div>';

            }

        }
        else{
            echo '<p>There are no images. Please insert some images.</p>';
        }
        ?>
    </div>

</body>
</html>