How to Upload a File in PHP using jQuery - onlyxcodes

Friday 10 September 2021

How to Upload a File in PHP using jQuery

This article will teach you how to use jQuery File Upload PHP with an Ajax method. On this blog, I've already written a tutorial on how to upload files.


However, in this post, I'm using ajax, which allows us to upload files or images more rapidly. The Ajax approach improves the user experience by allowing the webserver to respond significantly faster. It just refreshes active components in real-time, rather than reloading the entire page.


This tutorial shows how to use ajax() to upload an image to the server without having to reload the entire page. The image will be seen with the bootstrap alert successfully message on the same page after it has been uploaded.


At the back-end, PHP code would be used to choose and upload an image, with the uploading process being handled by the jQuery ajax() function. Let’s see the image upload ajax PHP example.


jQuery File Upload PHP - image upload ajax php - upload image jquery - upload file using ajax jquery

Table Content

1. Creating Database

2. Project Directory Structure

3. Database Connection Utility

4. Create Simple HTML Form

5. Include jQuery library

6. Implement Ajax Code

7. PHP Script for Image Uploading

8. Demo of Testing Application


Creating Database

Open phpMyAdmin and create a new database with the name that you want. The SQL query for creating the database is mentioned below. I used the database called jquery_fileupload_db.


create database jquery_fileupload_db;

After establishing the database, select it and run the SQL commands below to rapidly construct a table with two fields id and filename.


CREATE TABLE `tbl_file` (
  `id` int(11) NOT NULL,
  `filename` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Project Directory Structure

Take a look at the project directory I created in the XAMPP server's htdocs folder. Include this project in the www folder if you're using a WAMP server.


xampp/
├── htdocs/
	├── jQuery-File-Upload-PHP/
		├── bootstrap/
			├── css/
			│	└── bootstrap.min.js
			├── js/
			│	└── bootstrap.min.js
			├── fonts/
			│	└── glyphicons-halflings-regular.eot
			│	└── glyphicons-halflings-regular.svg
			│	└── glyphicons-halflings-regular.ttf
			│	└── glyphicons-halflings-regular.woff
			│	└── glyphicons-halflings-regular.woff2
		├── js/
		│	└── jquery-1.12.4-jquery.min.js
		│   │
		├── upload/
		
dbconfig.php
index.php
upload.php

We just need three files to upload file using ajax jquery.


dbconfig.php – To connect to a MySQL database, you'll need a database connection file.


index.php – Simple HTML form file to accept valid image files.


upload.php – PHP file to upload the selected image to the server-side.


And jQuery Ajax code to upload an image without having to reload the page.


Database Connection Utility

This is a database connection file loaded with the PDO extension, so copy the mentioned script and save it as dbconfig.php, then insert it into the file.


<?php
$db_host="localhost"; 
$db_user="root";	
$db_password="";	
$db_name="jquery_fileupload_db";	

try
{
	$db=new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_password);
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOEXCEPTION $e)
{
	$e->getMessage();
}

?>

Create Simple HTML Form

I used the bootstrap package to create a simple HTML form within the index.php file that allows a user to upload images to the server.


The form has an image upload input type file field and an upload button for submitting selected images to the server.


I have included a division tag after the upload button. Look at the id attribute value "img_result" on this div tag. The uploaded image will preview in this div tag.


In the next step, we'll submit this form request using an Ajax method.


<form class="form-horizontal">
					
	<div class="form-group">
	<label class="col-sm-3 control-label">Choose File</label>
	<div class="col-sm-6">
	<input type="file" name="file" id="userfile" class="form-control"/>
	</div>
	</div>
				
	<div class="form-group">
	<div class="col-sm-offset-3 col-sm-6 m-t-15">
	<input type="button" id="btn_upload" class="btn btn-success btn-lg btn-block" value="Upload">
	</div>
	</div>
				
	<div class="form-group">
	<div id="img_result" class="col-sm-offset-3 col-sm-6 m-t-15" >
	</div>
	</div>
				
</form>

Look at the visual shows of this form below this style.


create simple html form - jQuery file upload example - simple jquery file upload

Include jQuery library

The jQuery library is necessary before beginning the Ajax code. Look at the jQuery library code below, which I included before closing the index.php file's </head> tag.


<script src="js/jquery-1.12.4-jquery.min.js"></script>

Implement Ajax Code

After the closing </body> tag in the index.php file, the JavaScript Ajax code begins below.


Inside the code below, I've generated a jQuery button click event because when the upload button is clicked, it triggers the action.


Next, I built a FormData() object and supplied the current form to it. You can also supply the form id instead of this.form.


The $.ajax() method uses the POST method to deliver the formData object request to the "upload.php" file. If an image is successfully uploaded, it will display a preview of the image along with the words uploaded successfully.


<script type="text/javascript">	
$(document).ready(function(){
	$('#btn_upload').click(function(e){	
			    
		e.preventDefault();
				
		var file = $('#userfile').val();
				
		if(file=='')
		{
			alert ('Please Select File !!! ');
		}
					
		var formData = new FormData(this.form);
				
		$.ajax({
			url:'upload.php',
			type:'post',
			data:formData,
			contentType:false,
			processData:false,
			success:function(response){
				$('#img_result').html(response);
				$('#userfile').val('');
			}
			});			
		});		
	});
</script>

More Explanation:


The upload button's id attribute is #btn_upload. This is how the button click event is triggered.


We use the preventDefault() method to disable the upload button from being clicked by default when the form is submitted.


The #userfile id attribute of the input type file is used by the .val() method to obtain the file value. The value of this attribute is saved in a file variable.


If the file value is blank as a result of the condition check, an alert popup with the relevant error message appears.


The FormData object is then created, and we use it to capture our form and submit it using the Ajax procedure.


We assign formData object to data property in $.ajax() method.


You can use multipart/form-data or set contentType to false. The FormData object is encoded and sent using the Content-Type: multipart/form-data encoding, which enables the sending of files.


According to the documentation for jQuery, the default value for processData is true, which means it will process and turn the data into a query string. This is set to false because we don't want to do it.


Within this <div id="img_result" > tag, the success function displays an uploaded image with a successful message. Because the id attribute value of this div tag is img_result.


PHP Script for Image Uploading

This is the upload.php file, which runs in the background and communicates with the server via the ajax method.


That file simply contains PHP code that will use ajax to upload an image to the directory "upload/." I've added image validation so that it will only upload valid extension images.


<?php

require_once "dbconfig.php";
		
if($_FILES['file']['name'] != '')
{	
	$fileName  =  $_FILES['file']['name'];
	$tempPath  =  $_FILES['file']['tmp_name'];
	$fileSize  =  $_FILES['file']['size'];	

	$upload_path = 'upload/'; // set upload folder path 
	
	$fileExt = strtolower(pathinfo($fileName,PATHINFO_EXTENSION)); // get image extension
		
	// valid image extensions
	$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); 
					
	// allow valid image file formats
	if(in_array($fileExt, $valid_extensions))
	{				
		//check file not exist our upload folder path
		if(!file_exists($upload_path . $fileName))
		{
			// check file size '5MB'
			if($fileSize < 5000000){
				move_uploaded_file($tempPath, $upload_path . $fileName); // move file from system temporary path to our upload folder path 
			}
			else{		
				
				$errorMsg = "Sorry, your file is too large, please upload 5 MB size";
				
				echo "<div class='alert alert-danger'> 
						<button type='button' class='close' data-dismiss='alert'>&times;</button>"
						.$errorMsg. 
					 "</div>";
			}
		}
		else
		{		
			$errorMsg = "Sorry, file already exists check upload folder";
			
			echo "<div class='alert alert-danger'> 
					<button type='button' class='close' data-dismiss='alert'>&times;</button>" 
					.$errorMsg.
				 "</div>";
		}
	}
	else
	{		
		$errorMsg = "Sorry, only JPG, JPEG, PNG & GIF files are allowed";
		
		echo "<div class='alert alert-danger'> 
				<button type='button' class='close' data-dismiss='alert'>&times;</button>" 
				.$errorMsg.
			 "</div>";
	}
	
	// if no error caused, continue ....
	if(!isset($errorMsg))
	{
		$stmt=$db->prepare('INSERT INTO tbl_file(filename) VALUES(:fname)'); //sql insert query						
		$stmt->bindParam(':fname',$fileName);	  
			
		if($stmt->execute())
		{
			$successMsg = "File Upload Successfully........";
			
			echo "<div class='alert alert-success alert-dismissible'> 
					<button type='button' class='close' data-dismiss='alert'>&times;</button>" 
					.$successMsg. 
				 "</div>";
					
			echo '<img src="upload/'.$fileName.'" style="width:350px; height:240px;">';		
		}
	}
}

?>

Full Code Explanation:


Row no 3 – Include the database's connection file.


require_once "dbconfig.php";

Row no 5 to 9 – The PHP superglobal array $_FILES[ ] stores the “file” file field key. The if condition ensures that the file name is not empty.


$fileName = $_FILES[file]['name'] – This array value determines the file's original name. 


$tempPath = $_FILES['file']['tmp_name'] – The temporary location that is uploaded to the file is retrieved from the it array. Use that information to move the uploaded file into our folder's path. 


$fileSize = $_FILES['file']['size'] – The file size is defined in bytes by this value of the array. 


if($_FILES['file']['name'] != '')
{	
	$fileName  =  $_FILES['file']['name'];
	$tempPath  =  $_FILES['file']['tmp_name'];
	$fileSize  =  $_FILES['file']['size'];

Row no 11 – Create the $upload_path variable and save the path to the upload folder on the server where the image will be uploaded.


$upload_path = 'upload/'; // set upload folder path

Row no 13 – This code gets information about a file path and saves it to the variable $fileExt.


The pathinfo() function delivers information about the path to a file. Only the extension is returned by PATHINFO EXTENSION. 


The strtolower() function lowercases all characters in a string. 


$fileExt = strtolower(pathinfo($fileName,PATHINFO_EXTENSION)); // get image extension

Row no 16 – Create an array with the valid image extensions jpeg, jpg, png, and gif using the array() function. The variable $valid_extensions is allocated to this array.


// valid image extensions
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif');  

Row no 19 – With this if condition check, you can enable valid file or image formats.


Understand this,


in_array($fileExt, $valid_extensions)


The in_array() function receives the $fileExt and $valid extensions parameters.


The $fileExt variable receives information about the file, such as its name, as we reviewed in the code for Row 13.


The $valid_extensions variable contains the array values jpeg, jpg, png, and gif, which we mentioned before in the Row no 16 code.


The in_array() function first looks for file information in the $fileExt variable, then searches the $valid_extensions array for the file extension values jpeg, jpg, png, and gif.


If the condition is valid, continue.


// allow valid image file formats
if(in_array($fileExt, $valid_extensions))
{

Row no 22 – The file_exists() function is used to verify whether or not a file has been uploaded to the server.


//check file not exist our upload folder path
if(!file_exists($upload_path . $fileName))
{

Row no 25 to 27 – The file size must be at least 5 MB if the condition check is valid.


The move_uploaded_file() function will move the file from the temporary location to the upload folder path if the above conditions are met.


// check file size '5MB'
if($fileSize < 5000000){
	move_uploaded_file($tempPath, $upload_path . $fileName); // move file from system temporary path to our upload folder path 
}

Row no 59 to 75 – If the $errorMSG variable does not contain any errors, the prepare() work process the insert query.


The bindParam () function in the PDO insert query binds the placeholder :fname parameter. The $fileName variable holds the value of this parameter.


If the condition is true, the execute() method will run the $stmt statement. The message "Send File Successfully" includes a witch attach bootstrap alert-success box.


In addition, I've included the server directory path as well as the concinnated uploaded image name.


<?php

if(!isset($errorMsg))
{
	$stmt=$db->prepare('INSERT INTO tbl_file(filename) VALUES(:fname)'); //sql insert query						
	$stmt->bindParam(':fname',$fileName);	  
			
	if($stmt->execute())
	{
		$successMsg = "File Upload Successfully........";
			
		echo "<div class='alert alert-success alert-dismissible'> 
				<button type='button' class='close' data-dismiss='alert'>&times;</button>" 
				.$successMsg. 
			 "</div>";
					
		echo '<img src="upload/'.$fileName.'" style="width:350px; height:240px;">';		
	}
}

?>

Note:- I haven't described any of the else conditions; as you can see, they all detect a specific image uploading error message, and all messages are sent through the bootstrap alert box of the incorrect class.


All error messages assigning to the $errorMsg variable. 


Demo of Testing Application

Select the file you want to upload and click the Upload button. As demonstrated below, once the image upload is complete, it will deliver a success message along with the image.


once the image upload is complete, it will deliver a success message along with the image.

If you choose a file type that isn't listed in the condition, such as pdf or doc, an error will appear as seen below.


check valid image extension - jQuery file upload example

If you select an image that has already been uploaded, you will receive a file already existing error message, as shown below.


check uploaded image already exists or not


Read Also:

Register Form Data using PHP, Ajax and MySQL


Download Codes

No comments:

Post a Comment

Post Bottom Ad