Upload Multiple Files Using PHP And MariaDB

Upload Files with PHP
Upload Files with PHP

Live stream set for 2025-08-15 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.

How to Upload Multiple Files in PHP (With MariaDB Integration)

Are you just starting out with PHP and want to learn how to build a multiple file upload system that saves filenames to a MariaDB database? You are in the right place.

In this post, you will learn:

  • How to build a multiple file upload form using HTML
  • How to handle file uploads securely with PHP (latest version)
  • How to store file names in a MariaDB database
  • How to manage uploads: insert, update, and delete records
  • Best practices for secure and clean file handling

Step 1: Create the HTML Upload Form

<form action="" method="post" enctype="multipart/form-data">
   <label>Select files to upload:</label>
   <input type="file" name="files[]" multiple />
   <input type="submit" name="submit" value="Upload Files">
</form>  

Step 2: PHP Script to Handle Multiple File Uploads (upload.php)

$host = 'localhost';
$db = 'file_uploads';
$user = 'your_user';
$pass = 'your_password';

$conn = new mysqli($host, $user, $pass, $db);

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

$uploadDir = "uploads/";
$allowedTypes = ['avif', 'jpg', 'jpeg', 'png', 'gif', 'pdf'];

if (isset($_POST['submit']) && !empty($_FILES['files']['name'][0])) {
    foreach ($_FILES['files']['name'] as $key => $name) {
        $tmpName = $_FILES['files']['tmp_name'][$key];
        $error = $_FILES['files']['error'][$key];
        $size = $_FILES['files']['size'][$key];

        $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
        
        if ($error === 0 && in_array($ext, $allowedTypes)) {
            $newName = uniqid() . '.' . $ext;
            $uploadPath = $uploadDir . $newName;

            if (move_uploaded_file($tmpName, $uploadPath)) {
               $stmt = $conn->prepare("INSERT INTO uploads (filename) VALUES (?)");
               $stmt->bind_param("s", $newName);
               $stmt->execute();
               $stmt->close();
               //echo "$name uploaded successfully.<br>";
               header("Location: " . $_SERVER['PHP_SELF']);
               exit;
            } else {
               echo "Error uploading $name.<br>";
            }
        } else {
            echo "$name is not a valid file type or has an error.<br>";
        }
    }
} else {
    echo "No files selected.";
}

$conn->close();

Step 3: MariaDB Table Structure

CREATE TABLE uploads (
    id INT AUTO_INCREMENT PRIMARY KEY,
    filename VARCHAR(255) NOT NULL,
    uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Bonus: Updating and Deleting Files

You can add update and delete features using simple SQL queries like:

Delete File

$stmt = $conn->prepare("DELETE FROM uploads WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();

Update File Name

$stmt = $conn->prepare("UPDATE uploads SET filename = ? WHERE id = ?");
$stmt->bind_param("si", $newFilename, $id);
$stmt->execute();

Always remember to remove the file from the server using:

unlink('uploads/' . $filename);

Best Practices

  • Always validate file types to avoid malicious uploads
  • Store files outside the web root if possible
  • Rename files to avoid name collisions
  • Use prepared statements to protect against SQL injection
  • Limit file size and number of files uploaded at once

Screenshots and Screencast

Multiple File Upload Form
Web Browser Displaying A Clean Multiple File Upload Form

Uploaded Files
Web Browser Displaying A List Of Uploaded Files

Delete Prompt
Web Browser Displaying A Delete File Prompt

Edit Filename Form
Web Browser Displaying Am Edit Filename Form

PHP Multiple File Upload Video

Further Learning

Book: Learning PHP

If you want to go deeper into PHP, check out my book:
Learning PHP on Amazon

Course: Learning PHP

Prefer video and interactive examples? Enroll in the full course:
Learning PHP Course

Need Help with PHP?

I offer one-on-one programming tutorials, project migration services, and custom PHP development.

Contact Me Here

Got questions? Drop them in the comments or message me directly.

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 *