Handle AJAX Multiple File Upload Using PHP And MariaDB

PHP & MariaDB Uploader (Backend Logic!)
PHP & MariaDB Uploader (Backend Logic!)

Live stream set for 2025-10-22 at 14:00:00 Eastern

Ask questions in the live chat about any programming or lifestyle topic.

This livestream will be on YouTube or you can watch below.


Beginner’s Guide: Secure File Uploads with PHP, AJAX, and MariaDB

In our previous tutorial, we focused on the frontend, using HTML5 and the Fetch API to create a sleek, drag-and-drop user interface for file uploads. That was all about making the user experience seamless.

Now, we shift our focus to the engine room: the backend. This is where the real work happens- where we secure the data, process the files, and permanently store information in our database. This guide will walk you through setting up a robust PHP script to handle the Fetch API requests and interact with a MariaDB database.

1. Understanding the Backend’s Role

The backend’s primary job is to process the data sent from the frontend securely and efficiently. For file uploads, this means:

  1. Validation: Checking file size, type, and quantity.
  2. Processing: Saving the file to a secure location on the server.
  3. Database Interaction: Recording the file’s information (like its name, path, and user ID) into the database.
  4. Action Handling: Managing operations like deletion and replacement.

2. Setting up the PHP Handler for Fetch

The frontend sends the files and other data to your PHP script via the Fetch API. On the backend, PHP reads this data from the global $_FILES superglobal array.

Your PHP handler needs to listen for a specific action passed in the request. For example, the request might include an action flag like ‘upload’, ‘delete’, or ‘replace’.

<?php
// PHP Script to handle AJAX/Fetch requests (e.g., upload_handler.php)

// 1. Database Connection Setup (Replace with your credentials)
$conn = new mysqli("localhost", "user", "password", "database");

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

// 2. Security and Setup
$upload_dir = 'uploads/'; // Ensure this directory exists and is writable!
// ... (Your security checks for user authentication would go here)

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file_data'])) {
    $action = $_POST['action'] ?? 'upload'; // Get the intended action

    foreach ($_FILES['file_data']['name'] as $key => $name) {
        // Basic security and sanitization before proceeding
        $safe_name = preg_replace("/[^A-Za-z0-9.]/", '_', $name);
        $temp_path = $_FILES['file_data']['tmp_name'][$key];
        $target_file = $upload_dir . basename($safe_name);

        if ($action === 'upload' && move_uploaded_file($temp_path, $target_file)) {
            // Success: Save details to MariaDB
            $stmt = $conn->prepare("INSERT INTO files (file_name, file_path) VALUES (?, ?)");
            $stmt->bind_param("ss", $safe_name, $target_file);
            $stmt->execute();
            // ... Respond to frontend
        } else {
            // Handle error or other actions
        }
    }
}
?>

3. Handling Replacement and Deletion Actions

This is where the power of a database comes in. To handle file replacement or deletion, you primarily interact with MariaDB.

File Deletion

When the frontend sends a ‘delete’ action along with a unique file ID:

  1. Delete from Server: Use PHP’s unlink() function to remove the physical file from the uploads/ directory.
  2. Delete from Database: Run a SQL DELETE command on your MariaDB table using the file ID.
DELETE FROM files WHERE id = [file_id];

File Replacement

When the frontend sends a ‘replace’ action:

  1. Get Old Data: Retrieve the existing file path from MariaDB using the old file’s ID.
  2. Upload New File: Save the new file to the server (as shown in Step 2).
  3. Remove Old File: Use unlink() to delete the original file.
  4. Update Database: Run a SQL UPDATE command to point the existing file ID to the new file name and path.
UPDATE files SET file_name = 'new_name.jpg', file_path = 'uploads/new_name.jpg' WHERE id = [file_id];

Screenshots and Screencast

Multiple File Upload Code
Gnome Text Editor Displaying Fetch URL For File Upload HTML Code

Multiple File Upload Handler
Gnome Text Editor Displaying PHP File Upload Code

Multiple File Upload Form
Web Browser Displaying A Drag And Drop Multiple File Upload Form

Multiple File Upload Failure
Web Browser Displaying A Failed Multiple File Upload

Uploaded Files In Database
Web Browser RUnning PHPMyAdmin Displaying A List Of Uploaded Files

PHP Multiple File Upload AJAX Video

Ready to Master PHP?

This backend process is a core skill for any serious web developer. If you’re a beginner ready to dive deep into PHP, I highly recommend checking out my resources:

Need hands-on help with your projects? I’m available for one-on-one programming tutorials and services like framework updates or migration.

Contact me for direct consultation:

https://ojambo.com/contact

Recommended Resources:

Disclosure: Some of the links above are referral (affiliate) links. I may earn a commission if you purchase through them - at no extra cost to you.

About Edward

Edward is a software engineer, web developer, and author dedicated to helping people achieve their personal and professional goals through actionable advice and real-world tools.

As the author of impactful books including Learning JavaScript, Learning Python, Learning PHP, Mastering Blender Python API, and fiction The Algorithmic Serpent, Edward writes with a focus on personal growth, entrepreneurship, and practical success strategies. His work is designed to guide, motivate, and empower.

In addition to writing, Edward offers professional "full-stack development," "database design," "1-on-1 tutoring," "consulting sessions,", tailored to help you take the next step. Whether you are launching a business, developing a brand, or leveling up your mindset, Edward will be there to support you.

Edward also offers online courses designed to deepen your learning and accelerate your progress. Explore the programming on languages like JavaScript, Python and PHP to find the perfect fit for your journey.

📚 Explore His Books – Visit the Book Shop to grab your copies today.
💼 Need Support? – Learn more about Services and the ways to benefit from his expertise.
🎓 Ready to Learn? – Check out his Online Courses to turn your ideas into results.

Leave a Reply

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