How to Get the Path of the Uploaded File in Jquery

php file upload

Uploading files from clients to servers is 1 of the of import features of whatever PHP application. Withal, the implementation of features with proper security and hassle-complimentary configuration could be tricky. Developers could utilize several PHP file upload scripts to ensure that the application offers this feature 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. Bank check if there are whatsoever errors in the upload
  8. Check that the file is nether the set file size limit
  9. How to Use reCAPTCHA in PHP Contact Form?
  10. Wrapping Upwards

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

Prerequisites

For this PHP file uploading instance, I presume that you lot take a PHP awarding installed on a web server. My setup is:

  • PHP 7.1
  • MySQL
  • JQuery/Ajax file

To make sure that that I don't become distracted past server-level issues, I decided to host my PHP application on Cloudways managed servers considering it takes care of server-level issues and has a bully devstack correct out of the box. You can try out Cloudways for gratuitous by signing for an account.

Go the ultimate tool list for Developers

We'll send a download link to your inbox.

Thank Yous

Your Ebook is on it'south Way to Your Inbox.

At present, that the configurations are prepare, I will side by side work on the File Uploading Script.

Related Manufactures:

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 every bit follows:

  • Create a Bootstrap powered HTML Upload form as the "frontend" of the script
  • Ajax scripts for file upload
  • Use 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 data. But to brand the form work with the file, <class> element must accept its method set up to Mail service because files tin not be sent to servers using the Get method.

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

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

<!doctype html> <html> <head lang="en"> <meta charset="utf-viii"> <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-doc-8">  <h1><a href="#" target="_blank"><img src="logo.png" width="80px"/>Ajax File Uploading with Database MySql</a></h1> <hr>   <class id="class" action="ajaxupload.php" method="post" enctype="multipart/form-data"> <div class="grade-group"> <label for="proper noun">Proper noun</characterization> <input type="text" class="class-command" id="name" name="proper name" placeholder="Enter name" required /> </div> <div course="form-grouping"> <label for="electronic mail">Email</label> <input type="e-mail" class="form-command" id="email" name="e-mail" placeholder="Enter email" required /> </div>  <input id="uploadImage" blazon="file" take="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> <hour> <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 niggling scrap of styling on the form. In this form, I take mentioned ajaxupload.php in the action attribute of the course.

Finish Wasting Fourth dimension on Servers

Cloudways handle server management for you then you lot tin focus on creating bang-up apps and keeping your clients happy.

Using jQuery & AJAX for File Upload Course

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

<script src="https://ajax.googleapis.com/ajax/libs/jquery/three.2.ane/jquery.min.js"></script>        
$(document).ready(part (due east) {  $("#grade").on('submit',(function(eastward) {   e.preventDefault();   $.ajax({          url: "ajaxupload.php",    blazon: "Post",    data:  new FormData(this),    contentType: false,          cache: fake,    processData:false,    beforeSend : function()    {     //$("#preview").fadeOut();     $("#err").fadeOut();    },    success: function(data)       {     if(information=='invalid')     {      // invalid file format.      $("#err").html("Invalid File !").fadeIn();     }     else     {      // view uploaded file.      $("#preview").html(data).fadeIn();      $("#class")[0].reset();      }       },      error: function(e)        {     $("#err").html(due east).fadeIn();       }               });  })); });

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

Configure and Connect MySQL Database With PHP

The adjacent pace is setting up and configuring the MySQL database. Go to the Cloudways Database Director and create a table named 'uploading'. The fields of this table are name, email, file_name. Alternatively, you could apply the following SQL query:

CREATE Tabular array `uploading` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `proper name` varchar(100) COLLATE utf8_unicode_ci NOT Null,  `electronic mail` varchar(100) COLLATE utf8_unicode_ci Not NULL,  `file_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,  PRIMARY Cardinal (`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 connectedness and select DB  $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);  if($db->connect_error){     die("Unable to connect database: " . $db->connect_error);  }

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 Central Index of this array is the proper name attribute on this <input type=''file' name="image" > field.

In this case, $_FILES["paradigm"] 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["prototype"]["tmp_name"] stores the proper noun of the designated temporary file $errorimg = $_FILES["image"]["error"] stores whatsoever error lawmaking resulting from the transfer ?>        

Once the file has been uploaded to the temporary folder and all its data saved in the assortment, 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 every bit follows:

  1. Bank check if there are any errors in the upload.
  2. Check if the file blazon is immune
  3. Check that the file is nether the set file size limit
  4. Check if the filename is valid (if the filename has a /, information technology will affect the destination path).
  5. Cheque that the file doesn't already exist at the target location (based on the proper noun).
  6. Finally, upload the file.

Allow'southward create the PHP script to deal with the functionality of file uploading. Create ajaxupload .php and type the post-obit 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['image']) { $img = $_FILES['image']['name']; $tmp = $_FILES['epitome']['tmp_name'];  // get uploaded file'southward 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['proper noun']; $email = $_POST['email'];  //include database configuration file include_once 'db.php';  //insert form data in the database $insert = $db->query("INSERT uploading (proper noun,email,file_name) VALUES ('".$proper noun."','".$email."','".$path."')");  //echo $insert?'ok':'err'; } }  else  { echo 'invalid'; } } ?>

Now that all the checks have been coded in, I volition motion 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 volition be saved. Where pathinfo() is the built-in function which volition return the filename and extension in carve up indexes.

Check if there are any errors in the upload

To cheque the error in the uploaded file, type in the post-obit code, If the fault is greater than zero and then there must exist an error in the process.

if($errorimg > 0){     die('<div course="alert alert-danger" function="alert"> An mistake occurred while uploading the file </div>');  }

Check that the file is under the ready 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.

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

Where move_uploaded_file is the role which will move the file from $myFile["tmp_name"] (temporary location) to "upload/" . $name (permanent location) also cheque the database table record will exist inserted.

insert file in database

How to Use reCAPTCHA in PHP Contact Course?

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

To place a reCAPTCHA on your PHP website, y'all must use a simple library that wraps around a reCHAPTCHA API. You tin 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:

require_once('recaptchalib.php'); $publickey = "your_public_key"; //you got this from the signup folio 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. 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. Get back and try information technology again." .          "(reCAPTCHA said: " . $resp->mistake . ")");   }    else {     // Your lawmaking here to handle a successful verification   } ?>          

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

A: To upload PHP scripts, the default maximum upload size is 128 MB. However, you can e'er increase its upload limit by editing the upload_max_filesize value from the php.ini file.

Q: Which the all-time PHP library for file uploading?

A: Though at that place are several files uploading PHP libraries available in the market, the all-time one to use is the HTML5 File Upload library. It is very like shooting fish in a barrel to use and the most popular library amongst the developers, as information technology simplifies file uploading and validation in a few quick steps.

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

A: You can hands download file uploading script from phpfileuploader.com, it provides an easy to use and highly avant-garde file uploading script that precisely upload files to the server without refreshing the folio. Using the script, y'all can easily upload multiple files and new additional files during the upload process.

Q: How to motion uploaded files in PHP?

A: To move the uploaded file to a new path/directory, yous can use the move_uploaded_file() function to operate. Information technology allows united states to easily move the files to a new location even if they are newly uploaded. Upon successful transfer, it returns TRUE and if caught any exception, returns Faux.

Wrapping Upward

In this tutorial, I demonstrated image and file upload in PHP using AJAX and jQuery. Hither is a functional demo of the application where you could see the app in action. In my side by side 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

Share This Article

Customer Review at

"Cloudways hosting has i of the all-time customer service and hosting speed"

Sanjit C [Website Developer]

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 electronic mail him at [electronic mail protected]

howardthadince.blogspot.com

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

0 Response to "How to Get the Path of the Uploaded File in Jquery"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel