PHP MySQLi jQuery Ajax File Upload with Type Validation

Share this Article
Reading Time: 7 minutes
177 Views

Inside this article we will see the concept i.e PHP MySQLi jQuery Ajax File Upload with Type Validation tutorial. This article contains the classified information about file upload like pdf, txt, csv, etc with type validation as well.

We will use PHP MySQLi for this file upload and validation. After validation we will save file data to database table. For file upload and validation using ajax jquery plugin will be used.

If you are looking for an article which gives you the understanding of File upload via Ajax then this article will help you to understand the things in a very clear way.

Learn More –

Let’s get started.

Create Database & Table

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE php_applications;

Inside this database, we need to create a table.

Table we need – files

CREATE TABLE `files` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `file_name` varchar(255) NOT NULL,
 `uploaded_on` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Application Folder Structure

You need to create a folder structure to develop this application in PHP and MySQLi. Have a look the files and folders inside this application –

Create a folder with name php-file-upload and create these 3 files into it. And also create a uploads/ folder. This is to store files. Make sure this folder should have sufficient permission to read and write files into it.

Database Configuration

Open dbconfig.php file from folder. Add these lines of code into it.

<?php
/*
 @Author: Sanjay Kumar
 @Project: PHP MySQLi jQuery Ajax File Upload with Type Validation
 @Email: onlinewebtutorhub@gmail.com
 @Website: https://onlinewebtutorblog.com/
*/

// Database configuration
$host   = "localhost";
$dbuser = "admin";
$dbpass = "Admin@123";
$dbname = "php_applications";

// Create database connection
$conn = new mysqli($host, $dbuser, $dbpass, $dbname);

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

Application Programming

Open index.php file and write this following code into it.

<?php
/*
 @Author: Sanjay Kumar
 @Project: PHP MySQLi jQuery Ajax File Upload with Type Validation
 @Email: onlinewebtutorhub@gmail.com
 @Website: https://onlinewebtutorblog.com/
*/
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <title>PHP MySQLi jQuery Ajax File Upload with Type Validation</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-12">
                <div class="card m-auto w-75">
                    <div class="card-header text-center text-white bg-dark">
                        <h4>PHP MySQLi jQuery Ajax File Upload with Type Validation</h4>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-success alert-dismissible" id="success" style="display: none;">
                            <button type="button" class="close" data-dismiss="alert">×</button>
                            File uploaded successfully
                        </div>
                        <form id="submitForm" enctype="multipart/form-data">
                            <div class="form-group">
                                <label><strong>Select File : </strong><span class="text-danger"> *</span></label>
                                <input type="file" class="form-control" name="file" id="file" multiple>
                                <span id="error" class="text-danger"></span><br>
                            </div>
                            <div class="form-group d-flex">
                                <button type="submit" name="upload" class="btn btn-primary">Upload</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        $(document).ready(function() {
            $("input").prop('required', true);
            $('#file').change(function() {
                var ext = this.value.match(/\.(.+)$/)[1];
                switch (ext) {
                    case 'txt':
                    case 'pdf':
                    case 'docx':
                    case 'csv':
                    case 'xlsx':
                        $('#error').text("");
                        $('button').attr('disabled', false);
                        break;
                    default:
                        $('#error').text("File must be of type txt,pdf,docx,csv,xlsx.");
                        $('button').attr('disabled', true);
                        this.value = '';
                }
            });
            $("#submitForm").on("submit", function(e) {
                e.preventDefault();
                $.ajax({
                    url: "process.php",
                    type: "POST",
                    cache: false,
                    contentType: false,
                    processData: false,
                    data: new FormData(this),

                    success: function(response) {
                        $("#success").show();
                        $("#success").fadeOut(5000);
                    }
                });
            });
        });
    </script>
</body>

</html>
      

Ajax Handler – Form Processor

Open process.php file and write this complete code into it.

<?php 
/*
 @Author: Sanjay Kumar
 @Project: PHP MySQLi jQuery Ajax File Upload with Type Validation
 @Email: onlinewebtutorhub@gmail.com
 @Website: https://onlinewebtutorblog.com/
*/

include "dbconfig.php";

if (isset($_FILES['file'])) {
    
    $file_name = $_FILES['file']['name'];    
    // $file_size = $_FILES['file']['size'];    
    $file_tmp = $_FILES['file']['tmp_name'];     
    // $file_type = $_FILES['file']['type'];        
        
    $stmt = $conn->prepare("INSERT INTO files (file_name) VALUES (?)");
    $stmt->bind_param("s", $file_name);
        
    if (move_uploaded_file($file_tmp ,"uploads/".$file_name)) {

        if ($stmt->execute()) {

            echo "<h5 class='alert alert-primary'>File inserted Successfully!</h5>";
        }else{

            echo "<h5 class='alert alert-primary'>Failed to insert File</h5>";
        }
    }else{
        echo "<h5 class='alert alert-primary'>Failed to insert File</h5>";
    }
}

Application Testing

Now,

URL: http://localhost/php-file-upload/index.php

Submit form with invalid file

Submit form with a valid file

Once, data will be saved inside database. You should see like this –

Download Complete Source Code

We hope this article helped you to PHP PHP MySQLi jQuery Ajax File Upload with Type Validation Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5