How To Upload Files To The Server In PHP

PHP File uploading tutorial

PHP, a versatile server-side scripting language, makes it relatively straightforward to implement file upload functionality. In this step-by-step tutorial you will learn how to upload files to the server through HTML form and as the server side language we will use PHP.

Step 1: Enable File Upload in PHP

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

enable file upload in PHP

As well as in the php.ini file, you can increase the upload_max_filesize according to your need. In the following image, the upload_max_filesize=2M, which means you can’t upload those files whose size is over 2MB.

increase upload_max_filesize in PHP

Step 2: Create the Project Folder

Open your xampp htdocs folder or your localhost www directory and create a new folder called php-file-uploading, this the project or app folder.

In this project folder create two files index.html and upload.php and one folder called uploads/

  • index.html – contain the HTML form to upload flies.
  • upload.php – contain the file uploading script.
  • uploads/ – Destination of the file to be uploaded.
php-file-uploading/
β”œβ”€β”€ uploads/
β”œβ”€β”€ index.html
└── upload.php

Step 3: Create HTML Form for Uploading Files

Create index.html at the root and add an HTML form in that allows users to select and submit files. Must add the enctype attribute set to "multipart/form-data" to enable file uploads. Here is the html code –

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

In this code the form will send a POST request to the upload.php when a user clicks the “Upload File” button. The name="file" is an important attribute because we can access the file in the upload.php via the name which is file.

Step 4: Create “upload.php” that Contains File Uploading Script

Create a PHP script called upload.php to handle the uploaded file. Here is the script for file uploading –

<?php
// Check if the form is submitted via POST method
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 uploaded 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.";
        }
    }
}

This code checks if a file has been uploaded via a POST request and then attempts to move it to a specified directory. Here’s a breakdown of the code with comments:

  • The script checks if the request method is POST.
  • It specifies the target directory ($targetDir) where the uploaded file will be moved.
  • It constructs the full path to the uploaded file using the target directory and the filename obtained from the $_FILES array.
  • It checks if the file already exists in the target directory. If it does, an error message is displayed.
  • If the file doesn’t exist, it attempts to move the uploaded file from its temporary location (tmp_name) to the target directory using move_uploaded_file() function.
  • Depending on the success of the file upload operation, appropriate success or error messages are displayed.

Step 5: 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 (error code) and each integer value indicates a special message. Read this.

<?php
// Check if the form is submitted via POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Specify the target directory for uploads
    $targetDir = "uploads/";

    // Check if the file upload encountered any errors
    if ($_FILES["file"]["error"] != UPLOAD_ERR_OK) {
        // Handle different upload error cases
        switch ($_FILES["file"]["error"]) {
            case UPLOAD_ERR_INI_SIZE:
                echo "The uploaded file exceeds the upload_max_filesize directive in php.ini.";
                break;
            case UPLOAD_ERR_FORM_SIZE:
                echo "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.";
                break;
            case UPLOAD_ERR_PARTIAL:
                echo "The uploaded file was only partially uploaded.";
                break;
            case UPLOAD_ERR_NO_FILE:
                echo "No file was uploaded.";
                break;
            case UPLOAD_ERR_NO_TMP_DIR:
                echo "Missing a temporary folder.";
                break;
            case UPLOAD_ERR_CANT_WRITE:
                echo "Failed to write file to disk.";
                break;
            case UPLOAD_ERR_EXTENSION:
                echo "A PHP extension stopped the file upload.";
                break;
            default:
                echo "Sorry, there was an unknown error uploading your file.";
        }
    } else {
        // Move the uploaded file to the specified directory
        $targetFile = $targetDir . basename($_FILES["file"]["name"]);
        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.";
        }
    }
}

Step 6: Limit the File Upload Size

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.';
} else{
    // File uploading code...
}

You can get the maximum allowed file upload size from php.ini using ini_get().

// Get the maximum allowed file upload size from php.ini
$maxUploadSize = ini_get('upload_max_filesize');

Step 7: 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.';
}else{
    // File uploading code...
}

Step 8: 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)
{
    // Extract file extension
    $fileExtension = pathinfo($originalFilename, PATHINFO_EXTENSION);
    
    // Generate unique filename using MD5 hash and current timestamp
    $newFilename = md5(uniqid()) . '-' . time() . '.' . $fileExtension;
    
    return $newFilename;
}

// Check if the form is submitted via POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $targetDir = "uploads/"; // Specify the target directory
    
    // Generate a unique filename for the uploaded file
    $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.";
        }
    }
}

Step 9: Upload Images and Store their Name in the Database

Storing image names in a database offers numerous benefits in terms of data management, organization, security, and integration, making it a preferred approach in many web development scenarios.

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 and a Table In the Database:

  • Database name: test the name is totally up to you.
  • Table name: uploaded_files you can give any name.

Use the following SQL code to create the uploaded_files table and its columns.

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 Script for Saving the File Name in the DB

<?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)
{
    // Extract file extension
    $fileExtension = pathinfo($originalFilename, PATHINFO_EXTENSION);
    
    // Generate unique filename using MD5 hash and current timestamp
    $newFilename = md5(uniqid()) . '-' . time() . '.' . $fileExtension;
    
    return $newFilename;
}

// Check if the form is submitted via POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $targetDir = "uploads/"; // Specify the target directory
    
    // Generate a unique filename for the uploaded file
    $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.";
        }
    }
}

Leave a Reply

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

We use cookies to ensure that we give you the best experience on our website. Privacy Policy