Chat with us, powered by LiveChat

This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Launch PHP Websites and Applications in seconds through our 1-Click App Install Launch Now!

How to Create Image and File Upload in PHP with jQuery AJAX

Updated on March 22, 2018

6 Min Read
php file upload
Reading Time: 6 minutes

Uploading files from clients to servers is one of the important features of any PHP application. However, implementation of feature with proper security and hassle-free configuration could be tricky. Developers could use several PHP file upload scripts to ensure that the application offers this feature seamlessly.

I will discuss a popular strategy that developers could integrate within their projects. In this article, I will show you how you can add PHP file upload functionality on your website using jQuery, AJAX and MySQL.

Prerequisites

For the purpose of this tutorial, I assume that you have a PHP application installed on a web server. My setup is:

  • PHP 7.1
  • MySQL
  • JQuery/Ajax file

To make sure that that I don’t get distracted by server level issues, I decided to host my PHP application on Cloudways managed servers because it takes care of server level issues and has a great devstack right out of the box. You can try out Cloudways for free by signing for an account.

PHP Hosting: Best PHP 7 & PHP 5.6 Web Hosting

Now, that the configurations are ready, I will next work on the File Uploading Script.

Related Articles:

Multiple Images and Files Upload in Laravel with Validation

Upload Image and File in CodeIgniter

The Process of File Uploading in PHP

The process of a complete PHP file uploading script is as follows:

  • Create a Bootstrap powered HTML Upload form as the “frontend” of the script
  • Ajax scripts for file upload
  • Apply security checks
  • Create PHP scripts to handle/process data

Create the HTML Form

The HTML form is the interface through which user interacts and submits the data. But to make form work with the file, it is important that <form> element must have its method set to POST because files can not be send to servers using the GET method.

Another important attribute is enctype which should be set to multipart/form-data. Last but not least, the file <input> type attribute should be set to file.

Create a file index.php in your PHP project and type in the following code.

<!doctype html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Ajax File Upload with jQuery and PHP</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<script type="text/javascript" src="js/jquery-1.11.3-jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">

<div class="col-md-8">

<h1><a href="#" target="_blank"><img src="logo.png" width="80px"/>Ajax File Uploading with Database MySql</a></h1>
<hr> 

<form id="form" action="ajaxupload.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="name">NAME</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter name" required />
</div>
<div class="form-group">
<label for="email">EMAIL</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email" required />
</div>

<input id="uploadImage" type="file" accept="image/*" name="image" />
<div id="preview"><img src="filed.png" /></div><br>
<input class="btn btn-success" type="submit" value="Upload">
</form>

<div id="err"></div>
<hr>
<p><a href="https://www.cloudways.com" target="_blank">www.Cloudways.com</a></p>
</div>
</div>
</div></body></html>

html ajax file uploading form

In this form, I have used Bootstrap Classes to apply a little bit of styling on the form. In this form, I have mentioned ajaxupload.php in the action attribute of the form. 

Get Your VueJS Handbook Now

Simple enter your email address and get the download link in your Inbox.

Thank You

Your Ebook is on it’s Way to Your Inbox.

Using jQuery & AJAX for File Upload Form

Since I will use jQuery & AJAX for submitting data and uploading the files, I will start by including the jQuery library first.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
$(document).ready(function (e) {
 $("#form").on('submit',(function(e) {
  e.preventDefault();
  $.ajax({
         url: "ajaxupload.php",
   type: "POST",
   data:  new FormData(this),
   contentType: false,
         cache: false,
   processData:false,
   beforeSend : function()
   {
    //$("#preview").fadeOut();
    $("#err").fadeOut();
   },
   success: function(data)
      {
    if(data=='invalid')
    {
     // invalid file format.
     $("#err").html("Invalid File !").fadeIn();
    }
    else
    {
     // view uploaded file.
     $("#preview").html(data).fadeIn();
     $("#form")[0].reset(); 
    }
      },
     error: function(e) 
      {
    $("#err").html(e).fadeIn();
      }          
    });
 }));
});

In above code using $ajax() method for send data to php also check the success data or error in data sending.

Configure and Connect MySQL Database With PHP

The next step is setting up and configuring the MySQL database. Go to the Cloudways Database Manager and create a table named ‘uploading’. The fields of this table are name , email , file_name. Alternatively, you could use the following SQL query:

CREATE TABLE `uploading` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,

`email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,

`file_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Next, create db.php to connect the database with the PHP application. Paste the following code snippet in the file:

<?php

//DB details

$dbHost = 'localhost';

$dbUsername = 'fkmc';

$dbPassword = '';

$dbName = 'fkc';

//Create connection and select DB

$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

if($db->connect_error){

   die("Unable to connect database: " . $db->connect_error);

}

Create PHP Script for File Uploading

When the user interacts with this form, the file is uploaded to the temporary folder and all the information about the file is stored in the multidimensional array known as $_FILES.The Key Index of this array is the name attribute on this <input type=’’file’ name=”image” > field.

In this case, $_FILES[“image”] is the index name.more information about the file is stored in the following indexes.

<?php 
$img = $_FILES["image"]["name"] stores the original filename from the client
$tmp = $_FILES["image"]["tmp_name"] stores the name of the designated temporary file
$errorimg = $_FILES["image"][“error”] stores any error code resulting from the transfer
?>

Once the file has been uploaded to the temporary folder and all its information saved in the array, move_uploaded_file() function is used to move the file from its present temporary location to a permanent location. The process of uploading the file is as follows:

  1. Check if there are any errors in the upload.
  2. Check if the file type is allowed
  3. Check that the file is under the set file size limit
  4. Check if the filename is valid (if filename has a /, it will effect the destination path) .
  5. Check that the file doesn’t already exist at the target location (based on the name).
  6. Finally, upload the file.

Let’s create the PHP script to deal with the functionality of file uploading. Create ajaxupload.php and type the following code in it.

<?php

$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp' , 'pdf' , 'doc' , 'ppt'); // valid extensions
$path = 'uploads/'; // upload directory

if(!empty($_POST['name']) || !empty($_POST['email']) || $_FILES['image'])
{
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];

// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));

// can upload same image using rand function
$final_image = rand(1000,1000000).$img;

// check's valid format
if(in_array($ext, $valid_extensions)) 
{ 
$path = $path.strtolower($final_image); 

if(move_uploaded_file($tmp,$path)) 
{
echo "<img src='$path' />";
$name = $_POST['name'];
$email = $_POST['email'];

//include database configuration file
include_once 'db.php';

//insert form data in the database
$insert = $db->query("INSERT uploading (name,email,file_name) VALUES ('".$name."','".$email."','".$path."')");

//echo $insert?'ok':'err';
}
} 
else 
{
echo 'invalid';
}
}
?>

Now that all the checks have been coded in, I will move the uploaded file from the tmp folder to the upload folder. For this, first create a upload folder in the project directory. This is where the uploaded pictures will be saved.Where pathinfo() is the built–in function which will return the filename and extension in separate indexes.

Check if there are any errors in the upload

To check the error in the uploaded file, type in the following code, If the error is greater than zero then there must be an error in the process.

if($errorimg > 0){

   die('<div class="alert alert-danger" role="alert"> An error occurred while uploading the file </div>');

}

Check that the file is under the set file size limit

File size is measured in bytes. So, if the file size is set at 500kb, then the file size should be less than 500000.

if($myFile['size'] > 500000){

   die('<div class="alert alert-danger" role="alert"> File is too big </div>');

}

Where move_uploaded_file is the function which will move the file from $myFile[“tmp_name”] (temporary location) to “upload/” . $name (permanent location) also check the database table record will be inserted.

insert file in database

Wrapping Up

In this tutorial, I demonstrated image and file upload in PHP using AJAX and jQuery. Here is a functional demo of the application where you could see the app in action. In my next tutorial, I will demonstrate how you could upload and store a file into the database using PDO.

Share your opinion in the comment section. COMMENT NOW

Saquib Rizwan

Saquib is a PHP Community Expert at Cloudways - A Managed PHP Hosting Cloud Platform. He is well versed in PHP and regularly contributes to open source projects. For fun, he enjoys gaming, movies and hanging out with friends. You can email him at saquib.rizwan@cloudways.com

Launch PHP websites without the worry of Server Management.

Pre-Installed Optimized Stack with Git, Composer & SSH

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

THERE’S MORE TO READ.