Introduction

File uploads are a common feature in web development, allowing users to share images, documents, and other types of files. PHP provides simple yet powerful functionality to handle file uploads securely. In this tutorial, we’ll walk through the process of uploading files to a server using PHP.

Setting Up the Environment

Before we start, ensure you have a working web server environment with PHP installed. You can use platforms like XAMPP, WAMP, or set up a local server environment manually.

Creating the HTML Form: Let’s begin by creating an HTML form that allows users to select a file for upload.

<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select file to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload File" name="submit">
</form>

</body>
</html>

This form contains an input field of type “file” where users can select the file they want to upload. The form’s action attribute is set to “upload.php”, where we’ll handle the file upload process.

Handling File Uploads in PHP: Now, let’s create the PHP script (upload.php) that will handle the file upload process.

<?php
$targetDirectory = "uploads/images/";
$targetFile = $targetDirectory . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if ($check !== false) {
    // Allow certain file formats
    if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
        && $imageFileType != "gif") {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    } else {
        // if everything is ok, try to upload file
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
            echo "The file " . htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
} else {
    echo "File is not an image.";
    $uploadOk = 0;
}
?>

In this script, we define the target directory where the file will be uploaded (“uploads/images/”). We also define the target file path based on the original file name provided by the user. Then, we perform validations such as checking if the file is an image and if it meets certain criteria (e.g., file format). Finally, we move the uploaded file to the target directory.

PHP | pathinfo( ) Function

The pathinfo() is an inbuilt function which is used to return information about a path using an associative array or a string. 
The returned array or string contains the following information: 
 

  • Directory name
  • Basename
  • Extension

The path and options are sent as a parameters to the pathinfo() function and it returns an associative array containing the following elements directory name, basename, extension if the options parameter is not passed.
Syntax:  pathinfo(path, options)

Parameters Used: 
The pathinfo() function in PHP accepts two parameters.  

  1. path : It is a mandatory parameter which specifies the path of the file.
  2. options : It is an optional parameter which can used to restrict the elements returned by the pathinfo() function. By default it returns all the possible values which are directory name, basename, extension. 
    Possible values can be restricted using :
    • PATHINFO_DIRNAME – return only dirname
    • PATHINFO_BASENAME – return only basename
    • PATHINFO_EXTENSION – return only extension


Return Value: 
It returns an associative array containing the following elements directory name, basename, extension if the options parameter is not passed.
Errors And Exceptions:  

  1. PATHINFO_EXTENSION returns only the last extension, if the path has more than one extension.
  2. No extension element is returned, if the path does not have an extension.
  3. If the basename of the path starts with a dot, the following characters are interpreted as extension, and the filename is empty.
Input : print_r(pathinfo("/documents/gfg.txt"));
Output : Array
         (
          [dirname] => /documents
          [basename] => gfg.txt
          [extension] => txt
         )

Input : print_r(pathinfo("/documents/gfg.txt", PATHINFO_DIRNAME));
Output : /documents

Input : print_r(pathinfo("/documents/gfg.txt", PATHINFO_EXTENSION));
Output : txt

Input : print_r(pathinfo("/documents/gfg.txt", PATHINFO_BASENAME));
Output : gfg.txt

Upload Multiple Files using PHP

To upload multiple files using PHP, you can utilize the same HTML form structure but with slight modifications to handle multiple file inputs. Additionally, in the PHP script, you’ll need to loop through each uploaded file to process and move them to the desired location. Here’s how you can achieve this:

HTML Form:

<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select files to upload:
    <input type="file" name="filesToUpload[]" id="filesToUpload" multiple>
    <input type="submit" value="Upload Files" name="submit">
</form>

</body>
</html>

PHP Script (upload.php):

<?php
$targetDirectory = "uploads/images/";

// Check if files are uploaded
if(isset($_FILES['filesToUpload'])) {
    $errors = [];
    
    foreach($_FILES['filesToUpload']['tmp_name'] as $key => $tmp_name) {
        $file_name = $_FILES['filesToUpload']['name'][$key];
        $file_size = $_FILES['filesToUpload']['size'][$key];
        $file_tmp = $_FILES['filesToUpload']['tmp_name'][$key];
        $file_type = $_FILES['filesToUpload']['type'][$key];
        
        // Ensure the file is uploaded successfully
        if ($file_size > 0) {
            $targetFile = $targetDirectory . basename($file_name);

            // Move the uploaded file to the target directory
            if (move_uploaded_file($file_tmp, $targetFile)) {
                echo "The file " . htmlspecialchars(basename($file_name)) . " has been uploaded.<br>";
            } else {
                $errors[] = "Sorry, there was an error uploading your file.";
            }
        }
    }

    // Display any errors encountered during upload
    if (!empty($errors)) {
        foreach ($errors as $error) {
            echo $error . "<br>";
        }
    }
}
?>

Explanation:

  • In the HTML form, we’ve set the input type to “file” with the name attribute as an array (name="filesToUpload[]") to allow multiple file selection.
  • In the PHP script, we loop through each uploaded file using a foreach loop.
  • Inside the loop, we access various properties of the uploaded file such as name, size, tmp_name, and type.
  • We then construct the target file path and move each uploaded file to the specified directory.
  • Any errors encountered during the upload process are collected in an array and displayed to the user.

With this setup, users can select and upload multiple files simultaneously. The PHP script will handle each uploaded file individually and move them to the desired location on the server.

Conclusion

Congratulations! You’ve learned how to upload files to a server using PHP. This functionality opens up a wide range of possibilities for creating dynamic and interactive web applications. Experiment with different file types and validation criteria to enhance the functionality according to your project’s requirements.

Similar Posts

Leave a Reply

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