When we upload the files in PHP it means we move the files from one location to another. Generally, if we talk about the PHP file upload, then we know that in every request of the client to the server, the server returns the response with the required data. So, in case of PHP file upload mainly we move the files from one path to another. In the normal process of PHP file upload, when you click on the button for uploading the files, the form gets to reload. So, today in this post, I will be helping you in uploading the files without refreshing the form. So, I will use the jQuery and Ajax technique. I already posted tutorials on the PHP Ajax technique using jQuery. So let’s continue.
PHP File Upload
Before moving to the functions let’s know about the file and its attributes. PHP supports the various type of files to upload like image, txt, pdf, doc, etc. Before uploading, you can validate the type of file by the extension of the file. These are the default attributes of the file in the PHP –
- name – It defines the name of the file which is uploading.
- size – This identifies the size of the file.
- type – This is for the type of the file.
- tmp_name – It is about the temporary location of the file.
In this tutorial, I will create a new project for Ajax file upload PHP. I will use the PHP OOPs methodology to make our project code modular and convenient. So, open the editor and start creating a new project folder.
So, in the initial step, I will create the database and the connection for the project using the OOPs.
Ajax PHP Form Handling Using jQuery
Create MySQL Database and Database Connection
Create Database
- Open phpMyAdmin and create a new database with any name. Below is the SQL statement for creating the database. (in my case it is ajax_file_upload)
create database ajax_file_upload;
Create Database Connection
In the previous tutorial, we had seen the database connectivity using OOPs in the PHP
- Open the project folder and create a new PHP file (db-config.php) which will create the connection between the database and the application.
- Here is the code of the db-config.php file. Simply paste it in your file and replace the database credentials like password and the database name.
<?php
class DBController {
private $hostname = "localhost";
private $username = "root";
private $password = "root";
private $db = "ajax_file_upload";
// ----------- [ Creating connection ] ---------------
public function connect() {
$conn = new mysqli($this->hostname, $this->username, $this->password, $this->db)or die("Database connection error." . $conn->connect_error);
return $conn;
}
// ---------- [ Closing connection ] -----------------
public function close($conn) {
$conn->close();
}
}
?>
Create File Upload PHP Form (UI)
Now, create a new file (index.php) and paste the below code there. I have used the CDN for the Bootstrap CSS and JavaScript.
<!doctype html>
<html lang="en">
<head>
<title> PHP File Upload Using Ajax And jQuery</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
<h4 class="text-center"> File Upload in PHP Using jQuery and Ajax </h4>
<form method="post" id="myForm" autocomplete="off" enctype="multipart/form-data">
<div class="row">
<div class="col-xl-6 col-lg-6 col-md-10 col-sm-12 col-12 m-auto shadow p-4">
<label for="file">Image </label>
<div class="form-group">
<input type="file" name="file" id="file" class="form-control">
</div>
<div class="form-group">
<button type="button" id="uploadBtn" class="btn btn-success"> Upload </button>
</div>
<div class="form-group">
<div id="result"></div>
</div>
</div>
</div>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"
integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"
integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous">
</script>
</body>
</html>
- Start the Apache and MySQL services in the XAMPP Control Panel.
- Run the project. It will look like this.
Load Data From MySQL Database in PHP Using jQuery and Ajax
Send Ajax Request For PHP File Upload
Now, I will create an Ajax request using jQuery to the PHP. Paste the below code in the index.php file at the bottom, after the jQuery CDN.
<script>
$(document).ready(function(){
$("#uploadBtn").click(function(){
var formData = new FormData(this.form);
$.ajax({
url: './upload.php',
type: 'POST',
data: formData,
contentType: false,
cache: false,
processData:false,
success:function(response) {
$("#result").html(response);
}
});
});
});
</script>
- In the above code, I have created the button click event in jQuery so that when the upload button will click, it will fire the event.
- Then, I have created an object of FormData() class and passed the current form. Rather than this.form, you can also pass the form id.
- In the ajax request, I am sending the form data to a URL (PHP file) named upload.php. So, let’s create a new file to handle the ajax request.
Ajax Request Handling For File Upload in PHP MySQL Database
Create a new file (upload.php) and paste the below code.
<?php
include_once './db-config.php';
include_once './file-controller.php';
if(isset($_POST)) {
$db = new DBController();
$conn = $db->connect();
if(!empty($_FILES['file'])) {
$fController = new FileController($conn);
$uploadResult = $fController->uploadFile($_FILES['file']);
if($uploadResult['status'] == "SUCCESS") {
echo "<div class='alert alert-success alert-dismissible'>" .$uploadResult['message'] . "</div>";
echo '<img src="./uploads/'.$uploadResult['image'].'" style="max-width: 540px;">';
}
elseif($uploadResult['status'] == "FAILED") {
echo "<div class='alert alert-danger alert-dismissible'>" .$uploadResult['message'] . "</div>";
}
else {
echo "<div class='alert alert-success alert-dismissible'>" .$uploadResult['message'] . "</div>";
}
}
}
?>
Here, at the top (line no. 3-4), I have included two PHP files-
- db-config.php and
- file-controller.php
- In the db-config.php file, I have created the database connection using OOPs, which, I’ve shown you above.
- The file-controller.php will contain the function to upload the file and also, It will store the file name into the database table.
- Then, I have checked if the request is POST type, then I have created the object of the DBController class which is in the db-config.php file.
- In, the next line (line no. 8), I have called the connect() function for establishing the connection in this file.
- Next, I have created a condition, If the file is not empty then it will move to the next step. So, I have created the object of the FileController class which is inside the file-controller.php file.
- So, now you’ll require to create a new file (file-controller.php). This file will contain the file upload functionalities.
File Upload in PHP MySQL Database
- Now, create a new file with the name file-controller.php and paste the below code there.
<?php
class FileController {
// --------------- [ Constructor ] --------------------------
public function __construct($conn) {
$this->conn = $conn;
}
// --------------- [ Upload Function ] -----------------------
public function uploadFile($file) {
$source_path = $file['tmp_name'];
$file_name = $file['name'];
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
$target_file_name = time()."-".time().".".$file_extension;
$target_directory = "./uploads/".$target_file_name;
$file_type = $file['type'];
$data = array();
// ------------ [ File Validation ] --------------------------
if($file_type != "image/gif" && $file_type != "image/jpg" && $file_type != "image/png" && $file_type != "image/jpeg" && $file_type !="image/png") {
$data['status'] = "FAILED";
$data['message'] = "Invalid file type. (File type only jpg, jpeg, gif, and png allowed)";
return $data;
}
if($file['size'] > 2048000) {
$data['status'] = "FAILED";
$data['message'] = "File size is larger than 2 MB";
return $data;
}
// ------------------ [ File upload ] ---------------
if(move_uploaded_file($source_path, $target_directory)) {
// ---------------[ Insert into database ] -----------------
$sql = "INSERT INTO image (img) VALUES ('".$target_file_name."')";
$result = $this->conn->query($sql);
if($result) {
$data['status'] = "SUCCESS";
$data['message'] = "File uploaded successfully.";
$data['image'] = $target_file_name;
}
}
return $data;
}
}
?>
- Create a new folder (uploads) in the same directory, in which the file will move during the file upload. (You can create the folder in another directory too, but in that case, you will have to put the full path of that folder in the target directory.)
- Before uploading any file, I have got the extension of the file by using the pathinfo() function.
- This function takes the file name as the parameter and will return the file extension.
Example –
pathinfo($file_name, PATHINFO_EXTENSION)
- I have used some sort of file validation before uploading. The file type and size is the default attribute of the file.
- So by using these attributes, I have validated the file type and the size.
- Once, the validation will be passed, the file will be uploaded into the specified folder (location).
- In the next step, you will have to insert the file name into the database table.
- Once the file name has been inserted into the database table, the function will return the result with status, message and filename.
Run the PHP File Upload Project
- Save and execute the project.
- Choose the file and click on the Upload button.
Once the file upload will complete, it will return the success message with the uploaded file as shown below.
- In the above result, you can see the file has uploaded in the uploads folder.
- If you select any other file type which is not specified in the condition then it will show the error as shown below.
Here, is the demo of the file uploading tutorial.
Drag and Drop Multiple File Upload in PHP Using Dropzone js
You can download the PHP File upload script from the below download button.
Conclusion
Finally, we have completed the File Upload in the PHP MySQL database using jQuery and Ajax. This post will help you in the Ajax file upload in PHP without refreshing the form. I hope, it will be interesting for you. So, keep practicing and enjoy coding. Thank you 🙂
Krishana Raj says
Such a greatfully explained .
Thanks a lot , Actually i was searching for this kind of tutorial and I got it . It is very well explained.
Krishna says
Thank you sir for this codes.