How to upload image using Bootstrap, ajax, php, pdo and mysql?

Hi there , I am going to show How to upload image using ajax, php, pdo and mysql?


Uploading file from client to server is one of the most popular feature of any web application.

Process of File uploading in php:
  1. Configure the php.ini file
  2. Create a file upload form using Bootstrap HTML
  3. Ajax scripts for the file upload
  4. file upload validation and upload process in php
  5. create config.php
  6. Add Insert query
1.Configure the php.ini file:
Search the following text "file_uploads" in php.ini file . and set it On.
file_uploads = On
 
2.Create a file upload form using Bootstrap HTML:
HTML form that allow users to choose the file they want to upload.
we should  use enctype as "multipart/form-data" 
In this form i used Bootstrap classes to apply little bit of styling on the form.
and used jquery / ajax
To create file upload form using Bootstrap HTML, type the following code:
index.html
<!DOCTYPE html>
<html lang="en">
   <head>
      <title>File upload</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">   
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.1/dist/jquery.validate.min.js"></script>
      <script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>
      <script src="js/ajax.js"></script>
 </head>
   <body>
      <div class="container">
         <h2>Upload File</h2>
         <form class="form-horizontal" action="#" enctype="multipart/form-data" id="upload_form" method="POST" accept-charset="utf-8" role="form" novalidate="true">
            <div class="form-group">
               <label class="control-label col-sm-2" for="username">Upload File:</label>
               <div class="col-sm-10">
                  <input type="file" class="form-control" id="img_file" name="img_file">
                  <div id="message" style="display:none;"></div>
               </div>
            </div>
            <div class="form-group">
               <div class="col-sm-offset-2 col-sm-10">
                  <input type="submit" class="btn btn-default" name="upload" value="Upload">
               </div>
            </div>
         </form>
      </div>
      <style type="text/css">
         .label {
         width: 100px;
         text-align: right;
         float: left;
         padding-right: 10px;
         }
         #upload_form label.error, .output {
         color: #FB3A3A;
         font-family:"Segoe UI";
         font-size:13px;
         margin-top:-10px;
         }
      </style>

   </body>
</html>
3.Ajax scripts for the file upload:
I used jquery/ajax for  submitting form data to server. ajax which is used to submit the data without reloading web page.
load following jquery libraries and css in head tag.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<script src="js/ajax.js"></script>
Handled jquery form validation using following libraries.
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.1/dist/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>

ajax.js
call $.ajax() inside  submitHandler: function() . $.ajax() which is used to send the formdata to php and will check the response whether it is success data or error data.
use  extension: "jpg|png|jpeg|gif" file for file extension validation. and define your custom validation message in message part as show below.
extension: "File extension must be jpg or png or jpeg or gif"



      <script type="text/javascript">
         $("#loading").hide();
         // When the browser is ready...
         $(document).ready(function(){
         // Setup form validation on the #signup element
         $("#upload_form").validate({
         
          // Specify the validation rules
          rules: {
           file_upload: {
            required: true,
            extension: "jpg|png|jpeg|gif"
           }
         
          },
         
          // Specify the validation error messages
          messages: {
         
           file_upload: {
            required: "Please upload a file",
            extension: "File extension must be jpg or png or jpeg or gif"
           }
          },
         
          submitHandler: function (form) {   
           $("#loading").show(); 
           var file_data = $('#img_file').prop('files')[0];
           var form_data = new FormData();                  
                    form_data.append('img_file', file_data);
           $.ajax({
            type: 'POST',
            dataType:'JSON',    
            url: 'upload_process.php',    
               contentType: false,
                        processData: false,
                        cache:false,
            data: form_data,
            success: function (json_data) {          
             var msg = json_data.msg;
             var flag = json_data.flag;     
             if (flag == 1) {
              $("#loading").hide();
              $("#message").html(msg).show();
              $("#upload_form").trigger('reset');
             } else {
              $("#message").html(msg).show();
              $("#upload_form").trigger('reset');
         
             }
            }
           });
          }
         });
         
         }); 
      </script>

4.File upload validation and upload process in php
The process of uploading the file is as follows
I handled following thins  in php.
  1. Check  File empty validation
  2. Check file extension validation
  3. Check file size validation
  4. Define target directory 
  5. finally, file upload
Create  "upload_process.php"and type following code.
include config.php to obtain db connectivity.
<?php
   include('config.php');
   
   if(isset($_FILES["img_file"]["name"])){
    $upload_dir = "upload/";
    $target_file = $upload_dir . basename($_FILES["img_file"]["name"]);
    $uploadOk = 1;
    $fileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
       if($fileType != "jpg" && $fileType != "png" && $fileType != "jpeg"
    && $fileType != "gif" ) {
        echo json_encode(array("flag"=>0,"msg"=>"<font style='color:#A80000;'>Only JPG, JPEG, PNG & GIF files are allowed.</font>"));      
        die();
    } else if ($_FILES["img_file"]["size"] <= 2048) {
        echo json_encode(array("flag"=>0,"msg"=>"<font style='color:#A80000;'>File size should be less than 2mb</font>"));      
        die();
    } else if (!move_uploaded_file($_FILES["img_file"]["tmp_name"], $target_file)) {
           echo json_encode(array("flag"=>1,"msg"=>"<font style='color:#A80000;'>Failed to upload.</font>"));      
        die();
       } else {
        $created_at = date('Y-m-d');
           $insert_img = $conn->prepare("INSERT INTO img(img_name, created_at)VALUES(:img_name, :created_at)");
              $insert_img->bindParam(':img_name', $_FILES["img_file"]["name"]);
              $insert_img->bindParam(':created_at', $created_at);
              $insert_img->execute();
              $is_inserted = $conn->lastInsertId();
              if($is_inserted>0){
                  echo json_encode(array('flag'=>1, 'msg'=>"<font style='color:#00cc00;'>File uploaded successfully</font>"));
                  die();
              }else{
                  echo json_encode(array('flag'=>0, 'msg'=>"<font style='color:#A80000;'>Failed to inserted</font>"));
                  die();
                 
              }
       }
   
   }else{
    echo json_encode(array("flag"=>0,"msg"=>"<font style='color:#A80000;'>Please upload a file</font>"));      
        die();
   }
   ?>
4.Create config.php for database connection. type the following code
we need to setup Database.
Lets create the DB called signup_db.
add a table called img. The users table will have the following columns

  1. id
  2. img_name
  3. created_at
  4. updated_at
We can create Database, using phpMyadmin.

config.php
<?php
   $servername = "localhost";
   $username = "root";
   $password = "";
   try {
       $conn = new PDO("mysql:host=$servername;dbname=img_upload", $username, $password);
       $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      
       }
   catch(PDOException $e)
       {
       echo "Connection failed: " . $e->getMessage();
       }
   ?> 
 
5.Add Insert Query:
add following code in upload_process.php to insert the data in table using pdo mysql
$created_at = date('Y-m-d');
           $insert_img = $conn->prepare("INSERT INTO img(img_name, created_at)VALUES(:img_name, :created_at)");
              $insert_img->bindParam(':img_name', $_FILES["img_file"]["name"]);
              $insert_img->bindParam(':created_at', $created_at);
              $insert_img->execute();
              $is_inserted = $conn->lastInsertId();
              if($is_inserted>0){
                  echo json_encode(array('flag'=>1, 'msg'=>"<font style='color:#00cc00;'>File uploaded successfully</font>"));
                  die();
              }else{
                  echo json_encode(array('flag'=>0, 'msg'=>"<font style='color:#A80000;'>Failed to inserted</font>"));
                  die();
                 
              }

Hope you enjoyed code. Happy coding

Comments