Sharing is caring!

File Upload System with PHP

Table of Contents

Introduction to File Upload System

Hey there, fellow developers! πŸ‘‹ Have you ever needed a simple yet powerful way for users to upload, view, and manage files on your website?

PHP Projects

Well, you’re in luck! In this tutorial, we’re going to build a complete file upload system from scratch using PHP. This system will allow users to upload their files, view a list of all uploaded files, and even delete files when they’re no longer needed.

We’ll cover everything from setting up the project structure and connecting to the database to handling file uploads and deletions.

So, grab your favorite beverage, fire up your code editor, and let’s dive into the world of file management with PHP! πŸš€πŸ“‚

php exercises
php lab exercises
php mvc folder structure best practices
php mvc framework from scratch
php mvc from scratch
php mvc project
php photo database
php photo gallery
php practice exercises
php project source code
php projects source code
php projects with source code github
php realtime chat

Setting Up the Project

First, create a new directory for your project and set up the following structure. This will help keep your files organized:

file_upload_system/
β”‚
β”œβ”€β”€ uploads/
β”‚   └── (uploaded files will be stored here)
β”‚
β”œβ”€β”€ db.php
β”œβ”€β”€ index.php
β”œβ”€β”€ upload.php
β”œβ”€β”€ delete.php
└── styles.css

Ensure that the uploads directory is writable by your web server, as this is where the uploaded files will be stored.

1. Database Setup

We’ll use a database to keep track of the uploaded files. First, create a database named file_upload and a table called files to store information about the uploaded files. You can use the following SQL commands:

-- Create the database
CREATE DATABASE file_upload;

-- Use the database
USE file_upload;

-- Create the files table
CREATE TABLE files (
    id INT AUTO_INCREMENT PRIMARY KEY,
    filename VARCHAR(255) NOT NULL,
    filepath VARCHAR(255) NOT NULL,
    date_uploaded TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

This table will store the ID, filename, file path, and upload date for each uploaded file.

2. Connecting to the Database

Create a db.php file to handle the database connection. This file will be included in other scripts to provide database access.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "file_upload";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

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

This script connects to the MySQL database using the specified credentials. If the connection fails, it will output an error message.

3. Uploading Files

Create an upload.php file to handle file uploads. This script will save the uploaded file to the uploads/ directory and store the file information in the database.

Handling the File Upload

The following PHP script processes the file upload, moves the file to the uploads/ directory, and inserts the file information into the database:

<?php
include 'db.php'; // Include database connection

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }

    // Check file size (limit to 5MB)
    if ($_FILES["fileToUpload"]["size"] > 5000000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }

    // Allow certain file formats
    $allowed_types = array("jpg", "png", "jpeg", "gif", "pdf", "doc", "docx");
    if (!in_array($fileType, $allowed_types)) {
        echo "Sorry, only JPG, JPEG, PNG, GIF, PDF, DOC, and DOCX 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 (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            $filename = basename($_FILES["fileToUpload"]["name"]);
            $filepath = $target_file;

            // Insert file info into the database
            $sql = "INSERT INTO files (filename, filepath) VALUES (?, ?)";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ss", $filename, $filepath);

            if ($stmt->execute()) {
                echo "The file ". htmlspecialchars($filename). " has been uploaded.";
            } else {
                echo "Error: " . $stmt->error;
            }

            $stmt->close();
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }

    $conn->close();
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Upload File</title>
</head>
<body>
    <h1>Upload a File</h1>
    <form action="upload.php" method="post" enctype="multipart/form-data">
        <label for="fileToUpload">Select file to upload:</label>
        <input type="file" name="fileToUpload" id="fileToUpload" required><br>
        <input type="submit" value="Upload File" name="submit">
    </form>
</body>
</html>

This script handles the file upload process, checks for file size and type, and ensures no duplicate files are uploaded. Upon successful upload, the file information is stored in the database.

php mvc project source code
php photo database
php photo gallery
php project source code
php projects source code
php projects with source code
php real time application
php real time chat application
php realtime chat

4. Viewing Uploaded Files

Create an index.php file to list all uploaded files. Users can view or delete files from this page.

Displaying the Files

The following script fetches all uploaded files from the database and displays them in a table:

<?php
include 'db.php'; // Include database connection

// Fetch all files from the database
$sql = "SELECT * FROM files ORDER BY date_uploaded DESC";
$result = $conn->query($sql);
?>

<!DOCTYPE html>
<html>
<head>
    <title>File Upload System</title>
    <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
    <h1>Uploaded Files</h1>
    <a href="upload.php">Upload a New File</a>
    <table>
        <tr>
            <th>Filename</th>
            <th>Action</th>
        </tr>
        <?php
        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                echo "<tr>";
                echo "<td><a href='" . htmlspecialchars($row['filepath']) . "'>" . htmlspecialchars($row['filename']) . "</a></td>";
                echo "<td><a href='delete.php?id=" . $row['id'] . "' onclick='return confirm(\"Are you sure you want to delete this file?\");'>Delete</a></td>";
                echo "</tr>";
            }
        } else {
            echo "<tr><td colspan='2'>No files uploaded yet.</td></tr>";
        }
        ?>
    </table>
</body>
</html>

<?php
$conn->close();
?>

This script retrieves the list of uploaded files from the database and displays them in a table. Each file has a link to view the file and a link to delete it.

5. Deleting Files

Create a delete.php file to handle file deletion. This script will remove the file from the server and delete its record from the database.

Handling File Deletion

The following PHP script processes the file deletion:

<?php
include 'db.php'; // Include database connection

if (isset($_GET['id'])) {
    $file_id = $_GET['id'];

    // Fetch file information from the database
    $sql = "SELECT * FROM files WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $file_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $file = $result->fetch_assoc();
        $filepath = $file['filepath'];

        // Delete file from the server
        if (file_exists($filepath)) {
            unlink($filepath);
        }

        // Delete file record from the database
        $sql = "DELETE FROM files WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $file_id);

        if ($stmt->execute()) {
            echo "File deleted successfully.";
        } else {
            echo "Error: " . $stmt->error;
        }
    } else {
        echo "File not found.";
    }

    $stmt->close();
}

$conn->close();
?>
<a href="index.php">Go back to file list</a>

This script fetches the file information from the database, deletes the file from the server, and removes the corresponding record from the database.

file uploader design
file upload system design
design file sharing system
system design google drive
storage system design

6. Adding Some Style

Create a styles.css file to add some basic styling to your platform. This CSS file will style the forms, tables, and other elements to enhance the user experience.

Styling Your Platform

The following CSS provides basic styling for your file upload system:

body {
    font-family: Arial, sans-serif;
    margin: 20px;
    padding: 20px;
}

h1 {
    color: #333;
}

form {
    margin-top: 20px;
}

input[type="file"], input[type="submit"] {
    margin: 10px 0;
    padding: 10px;
}

table {
    width: 100%;
    border-collapse: collapse;
}

th, td {
    padding: 10px;
    border: 1px solid #ddd;
}

th {
    background-color: #f4f4f4;
}

a {
    color: #333;
    text-decoration: none;
}

a

:hover {
    text-decoration: underline;
}

This CSS adds basic styling to the body, forms, and tables to make the platform look cleaner and more organized.

Where are files uploaded to in PHP?

In PHP, when users upload files, they are temporarily stored in a system-defined directory. To make these files useful, you need to move them to a permanent location within your application’s structure.

Handling File Uploads in PHP

Create an Upload Form:

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

Process the Upload in PHP (upload.php):

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
    } elseif ($_FILES["fileToUpload"]["size"] > 5000000) {
        echo "Sorry, your file is too large.";
    } else {
        $fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
        $allowed_types = ["jpg", "png", "jpeg", "gif", "pdf", "doc", "docx"];
        if (!in_array($fileType, $allowed_types)) {
            echo "Sorry, only certain file types are allowed.";
        } else {
            if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
                echo "The file ". htmlspecialchars(basename($_FILES["fileToUpload"]["name"])). " has been uploaded.";
            } else {
                echo "Sorry, there was an error uploading your file.";
            }
        }
    }
}

Move the File: move_uploaded_file() moves the file from the temporary directory to uploads/.

This setup allows users to upload files to a permanent directory within your PHP application.

How to get uploaded file extension in PHP?

To get the uploaded file extension in PHP, use the pathinfo() function. Here’s a quick example:

$file_name = $_FILES["fileToUpload"]["name"];
$file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
echo "File extension: " . $file_extension;

This code extracts and prints the file extension of the uploaded file.

photo gallery php
php exercises
php exercises and solutions
php exercises and solutions pdf
php exercises online
php lab exercises
php mvc framework from scratch
php mvc from scratch

Which function is used to upload a file on a server in PHP?

In PHP, to upload a file to a server, you use the move_uploaded_file() function. This function is crucial for safely moving a file from its temporary location, where it is initially stored, to a permanent directory on the server.

When a file is uploaded via a form, PHP temporarily stores it in a system-defined directory. You need to specify where you want to move this file using move_uploaded_file(). This function takes two parameters: the temporary file path and the destination path where you want the file to be saved.

Here’s a simple example to illustrate how it works:

Assume you have an HTML form that allows users to upload a file:

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

In the corresponding upload.php file, you can handle the file upload as follows:

<?php
$target_dir = "uploads/"; // Directory where the file will be stored
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); // Full path for the file

// Move the file from temporary location to the target directory
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    echo "The file has been uploaded successfully.";
} else {
    echo "Sorry, there was an error uploading your file.";
}
?>

In this script:

  • $_FILES["fileToUpload"]["tmp_name"] provides the path to the temporary file.
  • move_uploaded_file() moves this temporary file to the uploads/ directory specified by $target_file.

Using move_uploaded_file() ensures that the file is securely transferred to the desired location on the server, allowing you to manage and utilize the uploaded file as needed.

How to get the name of uploaded file in PHP?

To get the name of an uploaded file in PHP, you use the $_FILES superglobal array, which holds information about the file being uploaded. This array contains various details about the uploaded file, such as its name, type, size, and temporary location.

When a user uploads a file through a form, PHP stores the file’s information in the $_FILES array. To access the original name of the file, you can refer to $_FILES["fileToUpload"]["name"], where "fileToUpload" is the name attribute of the file input field in your HTML form.

For example, if you have an HTML form that allows users to upload files:

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

In your PHP script (upload.php), you can retrieve and display the uploaded file’s name with the following code:

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Retrieve the original name of the uploaded file
    $file_name = $_FILES["fileToUpload"]["name"];

    // Display the file name
    echo "The name of the uploaded file is: " . htmlspecialchars($file_name);
}
?>

In this script:

  • $_FILES["fileToUpload"]["name"] provides the original name of the uploaded file, which is the name chosen by the user.
  • Using htmlspecialchars() ensures that the file name is safely displayed in the browser, preventing any potential security issues related to HTML output.

This approach allows you to easily access and work with the uploaded file’s name in your PHP application, making it straightforward to handle file uploads.

How to display an uploaded file in PHP?

To display an uploaded file in PHP:

  1. Upload the File: Use a form to upload the file and save it to a directory on the server.
  2. Display the File: Create a PHP script to serve the file based on its type.

Example of Uploading a File:

// upload.php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
    echo "<a href='display.php?file=" . urlencode(basename($target_file)) . "'>View File</a>";
}

Example of Displaying an Image:

// display.php
$file = isset($_GET['file']) ? $_GET['file'] : '';
$filepath = "uploads/" . $file;

if (file_exists($filepath)) {
    $extension = strtolower(pathinfo($filepath, PATHINFO_EXTENSION));
    switch ($extension) {
        case 'jpg':
        case 'jpeg':
            header('Content-Type: image/jpeg');
            break;
        case 'png':
            header('Content-Type: image/png');
            break;
        case 'gif':
            header('Content-Type: image/gif');
            break;
        default:
            header('Content-Type: application/octet-stream');
    }
    readfile($filepath);
} else {
    echo "File does not exist.";
}

This method lets you upload files to your server and display them appropriately.

How to handle uploaded file in PHP?

To handle an uploaded file in PHP:

  1. Upload the File:
    Use the $_FILES superglobal to get file details and move it to a permanent directory with move_uploaded_file().
   $target_dir = "uploads/";
   $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
   move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
  1. Check File Information:
    Validate the file type, size, and check for errors before moving the file.
   if ($_FILES["fileToUpload"]["error"] == UPLOAD_ERR_OK) {
       // Additional checks like file type and size can be done here
   }
  1. Handle File Display:
    Use headers to serve the file based on its type when displaying it.
   header('Content-Type: image/jpeg'); // For images
   readfile($target_file);

This process ensures that files are securely uploaded, validated, and displayed as needed.

How to check if a file was uploaded in PHP?

To check if a file was uploaded in PHP, you can use the $_FILES superglobal array. This array contains information about the file upload process. Here’s a concise guide:

  1. Check for Errors:
    Verify that there were no errors during the file upload by checking the error key in the $_FILES array. An error code of UPLOAD_ERR_OK (value 0) indicates a successful upload.
   if ($_FILES["fileToUpload"]["error"] == UPLOAD_ERR_OK) {
       echo "File uploaded successfully.";
   } else {
       echo "File upload failed with error code: " . $_FILES["fileToUpload"]["error"];
   }
  1. Verify the File Size:
    Check if the file size is greater than 0 to ensure that a file was indeed uploaded.
   if ($_FILES["fileToUpload"]["size"] > 0) {
       echo "File size is valid.";
   } else {
       echo "No file uploaded or file is empty.";
   }
  1. Check the File Temp Name:
    Confirm that the temporary file name is not empty, which indicates that the file was uploaded.
   if (!empty($_FILES["fileToUpload"]["tmp_name"])) {
       echo "Temporary file is available.";
   } else {
       echo "No temporary file available.";
   }

Example Code:

Here’s how you might integrate these checks into a complete script:

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if ($_FILES["fileToUpload"]["error"] == UPLOAD_ERR_OK) {
        if ($_FILES["fileToUpload"]["size"] > 0 && !empty($_FILES["fileToUpload"]["tmp_name"])) {
            echo "File uploaded successfully.";
        } else {
            echo "No file uploaded or file is empty.";
        }
    } else {
        echo "File upload failed with error code: " . $_FILES["fileToUpload"]["error"];
    }
}
?>

This script ensures that the file upload process is checked for errors and verifies that a file was indeed uploaded before proceeding.

What is file upload control?

A file upload control is like a magic button on your website that lets users pick files from their computer and send them over to your server. You create it using an <input> element with type="file", and it can be part of a form. Users can select one or multiple files at once, and you can even restrict the types of files they can upload with the accept attribute.

On the server side, PHP helps you handle these files with the $_FILES array. This array gives you all the details about the uploaded file and helps you move it to where you want it to be. It’s a simple yet powerful tool that makes handling file uploads easy and user-friendly!

Wrapping Up

Congratulations! You’ve now built a complete file upload system with the ability to upload, view, and delete files. Users can easily manage their files with this system, and you can further expand it with additional features like user authentication, advanced file management, and more.

If you have any questions or need further assistance, feel free to reach out. Happy coding! πŸš€πŸ“‚

Categories: PHP

0 Comments

Leave a Reply

Avatar placeholder

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