How to upload a file in PHP ?

In this article, we will explore how to upload a file in PHP using a form. First, let’s go over the necessary configurations.

Step 1: PHP Configuration
Ensure file uploads are enabled by updating the php.ini file. Set the file_uploads directive to On like this:

php.ini

file_uploads = On

Step 2: HTML Form Setup

In the index.html file, ensure the form’s enctype is set to multipart/form-data and the method is POST to allow file uploads.

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

Example :

Create an HTML file to upload files using a form with the POST method. It is crucial to use the POST method for file uploads.

<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>

Step 3: PHP File Upload Script

In uploading_file.php, we handle the file upload by storing the directory name and file information. Then, we check the directory’s existence, file extension validity, and size before uploading.

<?php
  $target_dir = $_POST["dirname"]."/";
  $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
  $uploadOk = 1;

  if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Check if directory exists
    if (!empty($_POST["dirname"])) {
      if (!is_dir($_POST["dirname"])) {
        mkdir($_POST["dirname"]);
      }
    } else {
      echo "Please specify a directory name.";
      $uploadOk = 0;
      exit;
    }

    // Validate the file
    if (isset($_FILES["fileToUpload"]) && $_FILES["fileToUpload"]["error"] == 0) {
      $allowed_ext = ["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"];
      $ext = pathinfo($file_name, PATHINFO_EXTENSION);

      if (!array_key_exists($ext, $allowed_ext)) {
        die("Error: Invalid file format.");
      }

      // Check file size (2MB max)
      $maxsize = 2 * 1024 * 1024;
      if ($file_size > $maxsize) {
        die("Error: File size exceeds the 2MB limit.");
      }

      // Move file to target directory
      if (in_array($file_type, $allowed_ext)) {
        if (!file_exists($target_file)) {
          if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            echo "File uploaded successfully.";
          } else {
            echo "Error uploading the file.";
          }
        } else {
          echo "File already exists.";
        }
      } else {
        echo "Error: Invalid file type.";
      }
    } else {
      echo "Error: " . $_FILES["fileToUpload"]["error"];
    }
  }
?>

Customizing File Extensions:
You can modify the allowed file extensions by editing the $allowed_ext array to meet your program’s requirements.

This process ensures proper validation of file size, extension, and directory existence, making the upload secure and efficient.

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *