Uploading Files with PHP

Uploading Files with PHP: A Step-by-Step Guide

Uploading files is a common feature in web development, allowing users to share images, documents, and more through web applications.

PHP, a versatile server-side scripting language, makes it relatively straightforward to implement file upload functionality. In this guide, we will walk through the essential steps to upload files using PHP.

Table of Contents #
  1. Configuration of the “php.ini” file
  2. HTML Form Setup
  3. PHP File Handling Script
  4. Handle file upload errors
  5. Limit the File Upload Size
  6. Limit the File Type
  7. Rename files Before Uploading
  8. Upload images and store the name into the database

1. 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 (By default, it is enabled).

php.ini file_uploads=on

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

php.ini pload_max_filesize=

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

2. HTML Form Setup:

To begin, create an HTML form that allows users to select and submit files. Use the enctype attribute set to “multipart/form-data” to enable file uploads. Include an input element of type “file” to facilitate file selection. Here’s a basic example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload Form</title>
</head>
<body>
    <form action="upload.php" method="post" enctype="multipart/form-data">
        <label for="file">Choose a file:</label>
        <input type="file" name="file" id="file">
        <input type="submit" value="Upload File">
    </form>
</body>
</html>

3. PHP File Handling Script:

Create a PHP script (upload.php in this case) to handle the uploaded file. Use the $_FILES superglobal to access file information.

The following PHP code validates and moves the uploaded file to a specified destination:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $targetDir = "uploads/"; // Specify the target directory
    $targetFile = $targetDir . basename($_FILES["file"]["name"]); // Get the file name

    // Check if file already exists
    if (file_exists($targetFile)) {
        echo "Sorry, the file already exists.";
    } else {
        // Move the file to the specified directory
        if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
            echo "The file has been uploaded successfully.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
}
?>

4. Handle file upload errors:

PHP provides the $_FILES["file"]["error"] variable, which indicates if any issues occurred during the upload. This variable contains an integer value and each integer value indicates a special message.

<?php
$error = $_FILES['file']['error'];
  • $error === 0 – There is no error, the file uploaded with success.
  • $error === 1 – The uploaded file exceeds the upload_max_filesize.
  • $error === 2 – The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
  • $error === 3 – The uploaded file was only partially uploaded.
  • $error === 4 – No file was uploaded.
  • $error === 6 – Missing a temporary folder.
  • $error === 7 – Failed to write file to disk.
  • $error === 8 – A PHP extension stopped the file upload.

5. Limit the File Upload Size

In PHP, you can check if the uploaded file exceeds the maximum allowed size before processing or saving it.

This is important to ensure that your script doesn’t attempt to handle files that are larger than the server’s configured limits. Here’s an example of how you can perform this check:

// Define the maximum allowed file size in bytes
$maxFileSize = 2 * 1024 * 1024; // 2 megabytes

if ($_FILES["file"]["size"] >= $maxFileSize) {
    echo 'File size exceeds the maximum allowed limit.';
}

6. Limit the File Type

It’s crucial to not only limit the file size but also validate and restrict the file types that are allowed to be uploaded.

This is important for security reasons to prevent users from uploading potentially harmful files.

Here’s an example of how you can limit the file types in a PHP file upload script:

// Define the allowed file types
$allowedFileTypes = ['jpg', 'jpeg', 'png', 'gif'];

// Get the file extension
$fileExtension = strtolower(pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION));

// Check if the file type is not allowed
if (!in_array($fileExtension, $allowedFileTypes))  {
    echo 'Invalid file type. Only ' . implode(', ', $allowedFileTypes) . ' are allowed.';
}

7. Rename files Before Uploading

When uploading files in PHP, you might want to rename the files before saving them to the server.

This can be useful for various reasons, such as avoiding naming conflicts, ensuring unique filenames, or implementing a consistent naming convention.

Here’s an example of how you can rename files before uploading them:

<?php
// Function to generate a unique filename
function generateUniqueFilename($originalFilename)
{
    $fileExtension = pathinfo($originalFilename, PATHINFO_EXTENSION);
    $newFilename = md5(uniqid()) . '-'. time() .'.' . $fileExtension;
    return $newFilename;
}


if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $targetDir = "uploads/"; // Specify the target directory
    $uniqueFilename = generateUniqueFilename($_FILES["file"]["name"]);
    $targetFile = $targetDir . basename($uniqueFilename);

    // Check if file already exists
    if (file_exists($targetFile)) {
        echo "Sorry, the file already exists.";
    } else {
        // Move the file to the specified directory
        if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
            echo "The file has been uploaded successfully.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
}

8. Upload images and store the name into the database

Below is an example script that demonstrates how to store name of the files into the database when uploading them.

This example assumes you have a MySQL database, but you can adapt it to other database systems.

Create a Database Table:

First, you need a table in your database to store file information. Here’s a basic example:

CREATE TABLE uploaded_files (
    id INT AUTO_INCREMENT PRIMARY KEY,
    file_name VARCHAR(255) NOT NULL,
    file_path VARCHAR(255) NOT NULL,
    upload_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

PHP File Upload Script:

<?php
// Database configuration
$dbHost = 'localhost'; // Your DB Host
$dbUser = 'root'; // Your DB User
$dbPass = ''; // Your DB Password
$dbName = 'test'; // Your DB Name

// Create database connection
$conn = new mysqli($dbHost, $dbUser, $dbPass, $dbName);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Function to generate a unique filename
function generateUniqueFilename($originalFilename)
{
    $fileExtension = pathinfo($originalFilename, PATHINFO_EXTENSION);
    $newFilename = md5(uniqid()) . '-'. time() .'.' . $fileExtension;
    return $newFilename;
}


if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $targetDir = "uploads/"; // Specify the target directory
    $uniqueFilename = generateUniqueFilename($_FILES["file"]["name"]);
    $targetFile = $targetDir . basename($uniqueFilename);

    // Check if file already exists
    if (file_exists($targetFile)) {
        echo "Sorry, the file already exists.";
    } else {
        // Move the file to the specified directory
        if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {

            // Store file information in the database
            $sql = "INSERT INTO uploaded_files (file_name, file_path) VALUES (?, ?)";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ss", $uniqueFilename, $targetFile);
            $stmt->execute();
            $stmt->close();

            echo "The file has been uploaded successfully.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
}