PHP - Simple Rename Image Upload Validation using Ajax

In this tutorial we will create a Simple Rename Image Upload Validation using Ajax. PHP is a server-side scripting language designed primarily for web development. Using PHP, you can let your user directly interact with the script and easily to learned its syntax. Using Ajax, data could then be passed between the browser and the server, using the XMLHttpRequest API, without having to reload the web page. So Let's do the coding...

Before we get started:

First you have to download & install XAMPP or any local server that run PHP scripts. Here's the link for XAMPP server https://www.apachefriends.org/index.html. And this is the link for the jquery that i used in this tutorial https://jquery.com/. Lastly, this is the link for the bootstrap that i used for the layout design https://getbootstrap.com/.

Creating Database

Open your database web server then create a database name in it db_rename, after that click Import then locate the database file inside the folder of the application then click ok. tut1

Creating the database connection

Open your any kind of text editor(notepad++, etc..). Then just copy/paste the code below then name it conn.php.
  1. <?php
  2.         $conn = new mysqli('localhost', 'root', '', 'db_rename');
  3.        
  4.         if(!$conn){
  5.                 die("Error: Failed to connect to database");
  6.         }
  7. ?>

Creating The Interface

This is where we will create a simple form for our application. To create the forms simply copy and write it into your text editor, then save it as index.php.
  1. <!DOCTYPE html>
  2. <html lang="en">
  3.         <head>
  4.                 <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
  5.                 <link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
  6.         </head>
  7. <body>
  8.         <nav class="navbar navbar-default">
  9.                 <div class="container-fluid">
  10.                         <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
  11.                 </div>
  12.         </nav>
  13.         <div class="col-md-3"></div>
  14.         <div class="col-md-6 well">
  15.                 <h3 class="text-primary">PHP - Simple Rename Image Upload Validation</h3>
  16.                 <hr style="border-top:1px dotted #ccc;"/>
  17.                 <div class="col-md-2"></div>
  18.                 <div class="col-md-8">
  19.                         <form method="POST" enctype="multipart/form-data">
  20.                                 <center>
  21.                                         <div id = "preview" style = "width:300px; height:300px; border:1px solid #000;">
  22.                                                 <center id = "lbl">[Photo]</center>
  23.                                         </div>
  24.                                         <br />
  25.                                         <input type = "file" id = "file" name = "file" /><br />
  26.                                         <div id="result"></div>
  27.                                         <button class="btn btn-primary" id="upload" type="button"><span class="glyphicon glyphicon-upload"></span> Upload</button>
  28.                                 </center>
  29.                         </form>
  30.                 </div>
  31.         </div>
  32. </body>
  33. <script src="js/jquery-3.2.1.min.js"></script>
  34. <script src="js/script.js"></script>
  35. </html>

Creating PHP Query

This code contains the php query of the application. This code will validate the file to be able to rename and send to the data. To do that just copy and write this block of codes inside the text editor, then save it as rename.php.
  1. <?php
  2.         require_once 'conn.php';
  3.         date_default_timezone_set("Etc/GMT-8");
  4.        
  5.        
  6.         if($_FILES['file']['name'] != ''){
  7.                 $allowed_ext = array("jpg", "png", "jpeg", "gif");
  8.                 $ext = explode(".", $_FILES['file']['name']);
  9.                 $end = end($ext);
  10.                
  11.                 if(in_array($end, $allowed_ext)){
  12.                         if($_FILES['file']['size'] < 1048576){
  13.                                 $name = date("Y-m-d").".".$end;
  14.                                 $path = "upload/".$name;
  15.                                
  16.                                 if(move_uploaded_file($_FILES['file']['tmp_name'], $path)){
  17.                                         $conn->query("INSERT INTO `image` VALUES('', 'img_name', '$path')");
  18.                                         echo "success";
  19.                                 }
  20.                                
  21.                         }else{
  22.                                 echo "File too large to upload";
  23.                         }
  24.                 }else{
  25.                         echo "Invalid file format";
  26.                 }
  27.         }else{
  28.                 echo "Please Select File!";
  29.                
  30.         }
  31.        
  32. ?>

Creating AjaxScript

This is where the main function of the application.This code will sent the file as a ajax request to be process in the php server. To do this just copy and write these block of codes inside the text editor, then save it as script.js inside the js folder.
  1. $(document).ready(function(){
  2.         var pic = $('<img id = "image" width = "100%" height = "100%"/>');
  3.         var lbl = $('<center id = "lbl">[Photo]</center>');
  4.         $("#file").change(function(){
  5.                 $("#lbl").remove();
  6.                 var files = !!this.files ? this.files : [];
  7.                 if(!files.length || !window.FileReader){
  8.                         $("#image").remove();
  9.                         lbl.appendTo("#preview");
  10.                 }
  11.                 if(/^image/.test(files[0].type)){
  12.                         var reader = new FileReader();
  13.                         reader.readAsDataURL(files[0]);
  14.                         reader.onloadend = function(){
  15.                                 pic.appendTo("#preview");
  16.                                 $("#image").attr("src", this.result);
  17.                         }
  18.                 }
  19.         });
  20.        
  21.         $('#upload').on('click', function(){
  22.                 var file_data = $('#file').prop('files')[0];
  23.                 var form_data = new FormData();
  24.                 form_data.append('file', file_data)
  25.                 console.log(form_data);
  26.                 $.ajax({
  27.                         url: 'rename.php',
  28.                         type: 'POST',
  29.                         processData: false,
  30.                         contentType: false,
  31.                         data: form_data,
  32.                         success: function(data){
  33.                                 if(data == "success"){
  34.                                         $("#image").remove();
  35.                                         lbl.appendTo("#preview");
  36.                                         $("#result").attr('class', 'alert alert-success');
  37.                                         $("#result").html("FIle uploaded!");
  38.                                 }else{
  39.                                         $("#result").attr('class', 'alert alert-danger');
  40.                                         $("#result").html(data);
  41.                                 }
  42.                         }
  43.                 });
  44.         });
  45. });
There you have it we successfully created Simple Rename Image Upload Validation using Ajax. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!!!

Add new comment