Friday, November 13, 2020

File Upload in PHP with jQuery AJAX

 Create a file index.php in your PHP project and copy and past the following code into your index.php file.

<!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>

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.

  1. <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 the above code using the $ajax() method for sending 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:

  1. CREATE TABLE `uploading` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT,
  3. `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  4. `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  5. `file_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  6. PRIMARY KEY (`id`)
  7. ) 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:

  1. <?php
  2. //DB details
  3. $dbHost = 'localhost';
  4. $dbUsername = 'root';
  5. $dbPassword = '';
  6. $dbName = 'fileUploadDb';
  7. //Create connection and select DB
  8. $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
  9. if($db->connect_error){
  10. die("Unable to connect database: " . $db->connect_error);
  11. }

Create a 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.

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

Once the file has been uploaded to the temporary folder and all its information saved in the array, the 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 the filename has a /, it will affect 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.

  1. <?php
  2. $valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp' , 'pdf' , 'doc' , 'ppt'); // valid extensions
  3. $path = 'uploads/'; // upload directory
  4. if(!empty($_POST['name']) || !empty($_POST['email']) || $_FILES['image'])
  5. {
  6. $img = $_FILES['image']['name'];
  7. $tmp = $_FILES['image']['tmp_name'];
  8. // get uploaded file's extension
  9. $ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
  10. // can upload same image using rand function
  11. $final_image = rand(1000,1000000).$img;
  12. // check's valid format
  13. if(in_array($ext, $valid_extensions))
  14. {
  15. $path = $path.strtolower($final_image);
  16. if(move_uploaded_file($tmp,$path))
  17. {
  18. echo "<img src='$path' />";
  19. $name = $_POST['name'];
  20. $email = $_POST['email'];
  21. //include database configuration file
  22. include_once 'db.php';
  23. //insert form data in the database
  24. $insert = $db->query("INSERT uploading (name,email,file_name) VALUES ('".$name."','".$email."','".$path."')");
  25. //echo $insert?'ok':'err';
  26. }
  27. }
  28. else
  29. {
  30. echo 'invalid';
  31. }
  32. }
  33. ?>

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 an 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.

  1. if($errorimg > 0){
  2. die('<div class="alert alert-danger" role="alert"> An error occurred while uploading the file </div>');
  3. }

Check that the file is under the set file size limit

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

  1. if($myFile['size'] > 500000){
  2. die('<div class="alert alert-danger" role="alert"> File is too big </div>');
  3. }

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.

How to Use reCAPTCHA in PHP Contact Form?

Recaptcha is a free service that protects forms from spamming and abusive submission. It’s an additional layer that works behind-the-scenes to prevent any spamming by differentiating if the end-user is a human or a bot, and give them the challenge to solve.

To place a reCAPTCHA on your PHP website, you must use a simple library that wraps around a reCHAPTCHA API. You can download the “reCAPTCHA PHP Library” and then use the file ‘recaptchalib.php’.

Add the following code in the <form> tag where you want your reCAPTCHA to be placed:

  1. require_once('recaptchalib.php');
  2. $publickey = "your_public_key"; //you got this from the signup page
  3. echo recaptcha_get_html($publickey);

To check whether the users have submitted the right answers or not, a “verify.php” file needs to be created and should be set as an ‘action’ parameter in the <form> tag. Here is the code below:

  1. <?php
  2. require_once('recaptchalib.php');
  3. $privatekey = "your_private_key";
  4. $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
  5. if (!$resp->is_valid) {
  6. die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
  7. "(reCAPTCHA said: " . $resp->error . ")");
  8. }
  9. else {
  10. // Your code here to handle a successful verification
  11. }
  12. ?>

No comments:

Post a Comment

Please Comment Here!

How to backup and download Database using PHP

< ?php $mysqlUserName = 'databaseusername' ; $mysqlPassword = 'databasepassword' ; $mysqlHostNa...