In this section, we will cover how to handle file uploads in PHP. File uploads are a common feature in web applications, allowing users to upload files such as images, documents, and other media. We will go through the process step-by-step, from creating an HTML form to handling the uploaded file on the server.

  1. Creating the HTML Form

First, we need an HTML form that allows users to select a file and submit it to the server.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>File Upload</title>
</head>
<body>
    <form action="upload.php" method="post" enctype="multipart/form-data">
        <label for="file">Choose file to upload:</label>
        <input type="file" name="file" id="file">
        <input type="submit" value="Upload File">
    </form>
</body>
</html>

Explanation:

  • action="upload.php": Specifies the server-side script that will handle the file upload.
  • method="post": Uses the POST method to submit the form data.
  • enctype="multipart/form-data": Necessary for file uploads to ensure the form data is encoded correctly.

  1. Handling the File Upload in PHP

Next, we need to create the upload.php script to handle the file upload.

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Check if a file was uploaded
    if (isset($_FILES['file']) && $_FILES['file']['error'] == 0) {
        $file = $_FILES['file'];

        // Define the target directory
        $targetDir = "uploads/";
        // Define the target file path
        $targetFile = $targetDir . basename($file["name"]);

        // Check if the file already exists
        if (file_exists($targetFile)) {
            echo "Sorry, file already exists.";
        } else {
            // Move the uploaded file to the target directory
            if (move_uploaded_file($file["tmp_name"], $targetFile)) {
                echo "The file " . htmlspecialchars(basename($file["name"])) . " has been uploaded.";
            } else {
                echo "Sorry, there was an error uploading your file.";
            }
        }
    } else {
        echo "No file was uploaded or there was an error uploading the file.";
    }
} else {
    echo "Invalid request method.";
}
?>

Explanation:

  • $_SERVER['REQUEST_METHOD'] == 'POST': Checks if the form was submitted using the POST method.
  • $_FILES['file']: Contains information about the uploaded file.
  • $_FILES['file']['error'] == 0: Checks if there were no errors during the file upload.
  • basename($file["name"]): Extracts the file name from the file path.
  • move_uploaded_file($file["tmp_name"], $targetFile): Moves the uploaded file from the temporary directory to the target directory.

  1. Validating the Uploaded File

It's important to validate the uploaded file to ensure it meets certain criteria, such as file type and size.

Example: Validating File Type and Size

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_FILES['file']) && $_FILES['file']['error'] == 0) {
        $file = $_FILES['file'];
        $targetDir = "uploads/";
        $targetFile = $targetDir . basename($file["name"]);
        $fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
        $maxFileSize = 2 * 1024 * 1024; // 2MB

        // Check file size
        if ($file["size"] > $maxFileSize) {
            echo "Sorry, your file is too large.";
        } 
        // Allow certain file formats
        elseif (!in_array($fileType, ['jpg', 'png', 'gif', 'pdf'])) {
            echo "Sorry, only JPG, PNG, GIF, and PDF files are allowed.";
        } 
        // Check if file already exists
        elseif (file_exists($targetFile)) {
            echo "Sorry, file already exists.";
        } 
        // Move the uploaded file to the target directory
        else {
            if (move_uploaded_file($file["tmp_name"], $targetFile)) {
                echo "The file " . htmlspecialchars(basename($file["name"])) . " has been uploaded.";
            } else {
                echo "Sorry, there was an error uploading your file.";
            }
        }
    } else {
        echo "No file was uploaded or there was an error uploading the file.";
    }
} else {
    echo "Invalid request method.";
}
?>

Explanation:

  • $maxFileSize = 2 * 1024 * 1024;: Sets the maximum file size to 2MB.
  • in_array($fileType, ['jpg', 'png', 'gif', 'pdf']): Checks if the file type is allowed.

  1. Practical Exercise

Exercise:

Create a PHP script that allows users to upload an image file. The script should:

  1. Validate that the uploaded file is an image (JPG, PNG, or GIF).
  2. Ensure the file size does not exceed 1MB.
  3. Save the uploaded file to a directory named images.
  4. Display a message indicating whether the upload was successful or if there were any errors.

Solution:

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_FILES['file']) && $_FILES['file']['error'] == 0) {
        $file = $_FILES['file'];
        $targetDir = "images/";
        $targetFile = $targetDir . basename($file["name"]);
        $fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
        $maxFileSize = 1 * 1024 * 1024; // 1MB

        // Check file size
        if ($file["size"] > $maxFileSize) {
            echo "Sorry, your file is too large.";
        } 
        // Allow certain file formats
        elseif (!in_array($fileType, ['jpg', 'png', 'gif'])) {
            echo "Sorry, only JPG, PNG, and GIF files are allowed.";
        } 
        // Check if file already exists
        elseif (file_exists($targetFile)) {
            echo "Sorry, file already exists.";
        } 
        // Move the uploaded file to the target directory
        else {
            if (move_uploaded_file($file["tmp_name"], $targetFile)) {
                echo "The file " . htmlspecialchars(basename($file["name"])) . " has been uploaded.";
            } else {
                echo "Sorry, there was an error uploading your file.";
            }
        }
    } else {
        echo "No file was uploaded or there was an error uploading the file.";
    }
} else {
    echo "Invalid request method.";
}
?>

Conclusion

In this section, we learned how to handle file uploads in PHP. We covered creating an HTML form for file uploads, handling the uploaded file on the server, and validating the file type and size. We also provided a practical exercise to reinforce the concepts learned. In the next section, we will discuss form security to ensure that our file upload functionality is secure.

PHP Programming Course

Module 1: Introduction to PHP

Module 2: Control Structures

Module 3: Functions

Module 4: Arrays

Module 5: Working with Forms

Module 6: Working with Files

Module 7: Object-Oriented Programming (OOP)

Module 8: Working with Databases

Module 9: Advanced PHP Techniques

Module 10: PHP Frameworks and Best Practices

Module 11: Project: Building a Web Application

© Copyright 2024. All rights reserved