Is It Better to Use Jquery or Php to Upload to Database?

php file upload

Uploading files from clients to servers is one of the important features of any PHP application. However, the implementation of features 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 characteristic seamlessly.

  1. Prerequisites
  2. The Procedure of File Uploading in PHP
  3. Create the HTML Course
  4. Using jQuery & AJAX for File Upload Form
  5. Configure and Connect MySQL Database With PHP
  6. Create a PHP Script for File Uploading
  7. Check if there are whatsoever errors in the upload
  8. Bank check that the file is under the set file size limit
  9. How to Utilise reCAPTCHA in PHP Contact Form?
  10. Wrapping Upward

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

Prerequisites

For this PHP file uploading case, I assume that you have a PHP application installed on a web server. My setup is:

  • PHP vii.1
  • MySQL
  • JQuery/Ajax file

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

Get the ultimate tool list for Developers

We'll ship a download link to your inbox.

Thank you

Your Ebook is on information technology's Manner to Your Inbox.

Now, that the configurations are ready, I volition adjacent 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 the user interacts and submits the information. But to brand the form work with the file, <form> element must have its method set to POST because files tin non be sent to servers using the GET method.

Another of import attribute is enctype which should be set to multipart/form-information. Last only not to the lowest degree, the file <input> type attribute should exist set to file.

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

<!doctype html> <html> <head lang="en"> <meta charset="utf-eight"> <title>Ajax File Upload with jQuery and PHP</title> <link rel="stylesheet" href="way.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/iii.three.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head> <trunk> <div course="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" activeness="ajaxupload.php" method="mail service" enctype="multipart/form-data"> <div class="grade-group"> <label for="name">NAME</label> <input blazon="text" class="form-command" id="proper noun" name="name" placeholder="Enter name" required /> </div> <div form="grade-group"> <label for="email">E-mail</label> <input type="e-mail" class="form-control" id="email" proper name="electronic mail" placeholder="Enter e-mail" required /> </div>  <input id="uploadImage" type="file" accept="prototype/*" name="prototype" /> <div id="preview"><img src="filed.png" /></div><br> <input class="btn btn-success" blazon="submit" value="Upload"> </class>  <div id="err"></div> <hr> <p><a href="https://world wide web.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 fiddling bit of styling on the form. In this form, I have mentioned ajaxupload.php in the activity attribute of the form.

Stop Wasting Fourth dimension on Servers

Cloudways handle server direction for you so you tin can focus on creating great apps and keeping your clients happy.

Using jQuery & AJAX for File Upload Form

Since I will use jQuery & AJAX for submitting information and uploading the files, I will kickoff past including the jQuery library first.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/iii.two.1/jquery.min.js"></script>        
$(document).gear up(office (e) {  $("#form").on('submit',(function(eastward) {   e.preventDefault();   $.ajax({          url: "ajaxupload.php",    blazon: "POST",    information:  new FormData(this),    contentType: false,          enshroud: false,    processData:imitation,    beforeSend : office()    {     //$("#preview").fadeOut();     $("#err").fadeOut();    },    success: role(information)       {     if(data=='invalid')     {      // invalid file format.      $("#err").html("Invalid File !").fadeIn();     }     else     {      // view uploaded file.      $("#preview").html(data).fadeIn();      $("#grade")[0].reset();      }       },      mistake: function(eastward)        {     $("#err").html(e).fadeIn();       }               });  })); });

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

Configure and Connect MySQL Database With PHP

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

CREATE TABLE `uploading` (  `id` int(11) Not Zilch AUTO_INCREMENT,  `proper 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 Non NULL,  Main KEY (`id`)  ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

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

<?php  //DB details  $dbHost = 'localhost';  $dbUsername = 'fkmc';  $dbPassword = '';  $dbName = 'fkc';  //Create connectedness and select DB  $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);  if($db->connect_error){     dice("Unable to connect database: " . $db->connect_error);  }

Create a PHP Script for File Uploading

When the user interacts with this grade, the file is uploaded to the temporary binder and all the data almost the file is stored in the multidimensional assortment known equally $_FILES .The Central Index of this array is the name attribute on this <input type=''file' name="paradigm" > field.

In this case, $_FILES["prototype"] is the index proper name.more data about the file is stored in the post-obit indexes.

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

Once the file has been uploaded to the temporary binder and all its data saved in the array, the move_uploaded_file() role 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 whatsoever errors in the upload.
  2. Check if the file blazon is allowed
  3. Bank check that the file is under the fix 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 lawmaking 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['epitome']) { $img = $_FILES['image']['name']; $tmp = $_FILES['image']['tmp_name'];  // get uploaded file's extension $ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));  // tin can upload same image using rand function $final_image = rand(1000,meg).$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['proper name']; $email = $_POST['electronic mail'];  //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."','".$electronic mail."','".$path."')");  //echo $insert?'ok':'err'; } }  else  { echo 'invalid'; } } ?>

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

Bank check if there are any errors in the upload

To check the error in the uploaded file, type in the post-obit code, If the error is greater than nix and then at that place must be an error in the process.

if($errorimg > 0){     dice('<div class="alert alert-danger" role="alert"> An fault occurred while uploading the file </div>');  }

Check that the file is under the set file size limit

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

if($myFile['size'] > 500000){     die('<div form="alert alert-danger" part="warning"> File is as well big </div>');  }

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

insert file in database

How to Utilise reCAPTCHA in PHP Contact Form?

Recaptcha is a free service that protects forms from spamming and abusive submission. It's an boosted layer that works behind-the-scenes to prevent any spamming past differentiating if the end-user is a man or a bot, and requite them the challenge to solve.

To place a reCAPTCHA on your PHP website, you lot must apply a elementary library that wraps around a reCHAPTCHA API. You can download the "reCAPTCHA PHP Library" and and so apply the file 'recaptchalib.php'.

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

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

To check whether the users take submitted the right answers or not, a "verify.php" file needs to exist created and should be set as an 'activeness' parameter in the <form> tag. Hither is the code below:

<?php   require_once('recaptchalib.php');   $privatekey = "your_private_key";   $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);   if (!$resp->is_valid) {     die ("The reCAPTCHA wasn't entered correctly. Go back and try it once more." .          "(reCAPTCHA said: " . $resp->fault . ")");   }    else {     // Your lawmaking hither to handle a successful verification   } ?>          

Q: How to modify the maximum upload file size in PHP?

A: To upload PHP scripts, the default maximum upload size is 128 MB. However, you can always increment its upload limit past editing the upload_max_filesize value from the php.ini file.

Q: Which the best PHP library for file uploading?

A: Though there are several files uploading PHP libraries available in the marketplace, the all-time one to use is the HTML5 File Upload library. It is very easy to use and the most pop library among the developers, as it simplifies file uploading and validation in a few quick steps.

Q: Where can I download the PHP file upload script?

A: You can easily download file uploading script from phpfileuploader.com, information technology provides an easy to use and highly advanced file uploading script that precisely upload files to the server without refreshing the page. Using the script, you can easily upload multiple files and new additional files during the upload process.

Q: How to move uploaded files in PHP?

A: To move the uploaded file to a new path/directory, you lot can utilise the move_uploaded_file() function to operate. It allows u.s.a. to easily move the files to a new location fifty-fifty if they are newly uploaded. Upon successful transfer, information technology returns Truthful and if caught any exception, returns FALSE.

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 meet the app in action. In my side by side tutorial, I will demonstrate how yous could upload and shop a file into the database using PDO .

Share your opinion in the annotate section. COMMENT At present

Share This Commodity

Customer Review at

"Cloudways hosting has one of the best customer service and hosting speed"

Sanjit C [Website Developer]

Saquib Rizwan

Saquib is a PHP Community Proficient 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 [email protected]

strehlowmakinged.blogspot.com

Source: https://www.cloudways.com/blog/the-basics-of-file-upload-in-php/

0 Response to "Is It Better to Use Jquery or Php to Upload to Database?"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel