Skip to content
Related Articles
Open in App
Not now

Related Articles

How to upload a file in PHP ?

Improve Article
Save Article
  • Last Updated : 01 Mar, 2022
Improve Article
Save Article

In this article, we will learn how to upload a file using PHP. Let us first understand some basic configurations.

Approach: In your “php.ini” file, search for the “file_uploads” parameter and set it to “On” as mentioned below.

file_uploads = On

In the “index.html” file, the enctype must be multipart/form-data and the method must be POST.

<form action="fileupload.php" 
    method="POST" enctype="multipart/form-data">

Example 1: First, we created an HTML file so that we can upload a file using a form through the post method, and also it is important to make sure that the method is post method.

In “uploading_file.php”, we first store the directory name and file information from the post method, and then we check for the existence of the directory, validity of extensions. We can check if the file size is less than the maximum file size along with the existence of the file so that we can upload the file after all the validations.

The extensions which are allowed can be changed or added in an array according to the requirements of the program.

index.html




<!DOCTYPE html>
<html>
  
<body>
    <form action="uploading_file.php" 
          method="post" 
          enctype="multipart/form-data">
        Directory<input type="text"
                        name="dirname" 
                        id="dirname">
        <br>
        Select image to upload:
        <input type="file" 
               name="fileToUpload" 
               id="fileToUpload">
        <br>
        <input type="submit" 
               value="Upload Image"
               name="submit">
    </form>
</body>
  
</html>


uploading_file.php




<!DOCTYPE html>
<?php
  
  $target_dir = $_POST["dirname"]."/";
  $target_file = $target_dir 
    . basename($_FILES["fileToUpload"]["name"]);
  $uploadOk = 1;
  
  if($_SERVER["REQUEST_METHOD"] == "POST") {
  
    // To check whether directory exist or not
    if(!empty($_POST["dirname"])) {
        if(!is_dir($_POST["dirname"])) {    
            mkdir($_POST["dirname"]);    
            $uploadOk = 1;            
        }
    }
    else {
        echo "Specify the directory name...";
        $uploadOk = 0;
        exit;    
    }
  
    // Check if file was uploaded without errors
    if(isset($_FILES["fileToUpload"]) && 
        $_FILES["fileToUpload"]["error"] == 0) {
        $allowed_ext = array("jpg" => "image/jpg",
                            "jpeg" => "image/jpeg",
                            "gif" => "image/gif",
                            "png" => "image/png");
        $file_name = $_FILES["fileToUpload"]["name"];
        $file_type = $_FILES["fileToUpload"]["type"];
        $file_size = $_FILES["fileToUpload"]["size"];
      
        // Verify file extension
        $ext = pathinfo($file_name, PATHINFO_EXTENSION);
  
        if (!array_key_exists($ext, $allowed_ext)) {
            die("Error: Please select a valid file format.");
        }    
              
        // Verify file size - 2MB max
        $maxsize = 2 * 1024 * 1024;
          
        if ($file_size > $maxsize) {
            die("Error: File size is larger than the allowed limit.");
        }                    
      
        // Verify MYME type of the file
        if (in_array($file_type, $allowed_ext))
        {
            // Check whether file exists before uploading it
            if (file_exists("upload/" . $_FILES["fileToUpload"]["name"])) {
                echo $_FILES["fileToUpload"]["name"]." is already exists.";
            }        
            else {
                if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], 
                  $target_file)) {
                    echo "The file "$_FILES["fileToUpload"]["name"]. 
                      " has been uploaded.";
                
                else {
                    echo "Sorry, there was an error uploading your file.";
                }
            }
        }
        else {
            echo "Error: Please try again.";
        }
    }
    else {
        echo "Error: ". $_FILES["fileToUpload"]["error"];
    }
}
?>
  
</body>
</html>


Output:

enter directory name and choose file

In the “uploads” folder of the working folder, the user can find the uploaded “gfg_sample.png” file.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!