fbpx
How to Create Image and File Upload in PHP with jQuery AJAX
August 3, 2022
File Upload in PHP

The hallmark of the PHP application is that it enables you to upload files from clients to servers. However, you need to be patient to implement features with stress-free configuration and correct security. As a developer, you can use different scripts for PHP file uploads to remain satisfied if you offer the feature seamlessly.

This blog post will discuss how to add PHP file upload functionality to a WordPress site through jQuery and AJAX.

Requirements

For PHP file uploading, you need to have a PHP application on your web server. Moreover, you need to fulfill the following requirements:

  • JQuery/Ajax file
  • MySQL
  • PHP 7.1

File Uploading in PHP – The Method

You can complete PHP file uploading using a script with the following steps:

·        Make an HTML Upload form as the script’s “frontend”

·        Use Ajax scripts for PHP file upload

·        Implement security checks

·        Write PHP scripts for data processing

HTML Form Creation

To interact with the users and data submission, you need the HTML form as an interface. However, to enable the form function with the file, you need to set the form element method as POST, as you can send files to servers through the GET method.

Also, a key attribute here is ‘enctype’ that you should set to ‘multipart or form-data.’ Lastly, the attribute of the file [<input> type] should be set to ‘file.’

So, make a file index.php in the PHP project you need and write the code below.

<!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://cloudpages.cloud” target=”_blank”>Cloudpages.cloud</a></p>

</div>

</div>

</div></body></html>

File Upload Form Through AJAX and jQuery

Here, we are using AJAX and jQuery to submit data and upload files. To begin, we include the jQuery library.  

$(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();

   }     

});

 }));

});

We have used the $ajax() method in the abovementioned script to send data to PHP. Make sure to check the error or success data in data sending.  

MySQL Database Connection and Configuration With PHP

In this step, we will set up and configure the MySQL database. To do this, you can implement the SQL query mentioned below:  

CREATE TABLE `uploading` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`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 NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Now, make db.php to link the PHP application with the database. Use the below code in your file:   

<?php

//DB details

$dbHost = ‘localhost’;

$dbUsername = ‘fkmc’;

$dbPassword = ”;

$dbName = ‘fkc’;

//Create connection and select DB

$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

if($db->connect_error){

   die(“Unable to connect database: ” . $db->connect_error);

}

PHP Script Creation for File Uploading

When your user interacts with the PHP script, the file goes to a temporary folder, and every piece of information about the file gets into the multidimensional array called $_FILES. The array’s Key Index is the name attribute on this field <input type=’’file’ name=” image” >.

Here, $_FILES[“image”] is the name of the index. Further information about the file is saved in these indexes.

<?php 

$img = $_FILES[“image”][“name”] stores the original filename from the client

$tmp = $_FILES[“image”][“tmp_name”] stores the name of the designated temporary file

$errorimg = $_FILES[“image”][“error”] stores any error code resulting from the transfer

?>

The move_uploaded_file() function transfers the file from its current temporary location to a permanent location after it is uploaded to the temporary folder and all of its information has been saved in the array. The following is the procedure for uploading the file:

  • Inspect whether there is any error in the upload
  • Inspect whether the file type is correct
  • Satisfy that the file is under the set file size limit
  • Inspect the validity of the filename (filename with a /will impact the destination path)
  • Make sure the target location doesn’t have the file (based on the name)
  • Lastly, upload your file 

You can create a PHP script to deal with the file uploading functionality. So, make ajaxupload.php and write the following programming lines:

<?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[‘image’][‘tmp_name’];

// get uploaded file’s 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[‘name’];

$email = $_POST[’email’];

//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.”‘,'”.$email.”‘,'”.$path.”‘)”);

//echo $insert?’ok’:’err’;

}

else 

{

echo ‘invalid’;

}

}

?>

We will shift the uploaded file from the tmp folder to the upload folder because every check has been entered into the code. Create an upload folder in the project directory before doing this. The images you post will be kept here.

Read Also: How to Install the PHP ImageMagick Extension

Check For Errors

To ensure there is no error in the uploaded file, write the following code. If you get an error more significant than zero, you must have committed any mistake in the process.

if($errorimg > 0){

   die(‘<div class=”alert alert-danger” role=”alert”> An error occurred while uploading the file </div>’);

}

Check Your File Size is Under the Limit

You can measure your file size in bytes. The uploaded images will be saved if the file size is set to 500kb, meaning the file size should be less than 500000.

if($myFile[‘size’] > 500000){

   die(‘<div class=”alert alert-danger” role=”alert”> File is too big </div>’);

}

How CloudPages Uploads Files over SFTP using PHP

Apart from jQuery and AJAX, SFTP can also be used to upload files in PHP which CloudPages uses. File transfer over SFTP can raise different problems and is not supported easily through PHP. However, .phpseclib can offer a robust library wrapper that enables seamless access to the SFTP protocol and different cryptography functions. phpseclib is completely interoperable with OpenSSL and other standardized cryptography protocols.

Below is an example script to upload a file to a remote server over SFTP in PHP.  

/* Set the correct include path to ‘phpseclib’. Note that you will need

   to change the path below depending on where you save the ‘phpseclib’ lib.

   The following is valid when the ‘phpseclib’ library is in the same

   directory as the current file.

 */

set_include_path(get_include_path() . PATH_SEPARATOR . ‘./phpseclib0.3.0’);

include(‘Net/SFTP.php’);

/* Change the following directory path to your specification */

$local_directory = ‘/localhost/my-files/’;

$remote_directory = ‘/my-files/’;

/* Add the correct FTP credentials below */

$sftp = new Net_SFTP(‘your_ftp_url’);

if (!$sftp->login(‘ftp_username’, ‘ftp_password’))

{

exit(‘Login Failed’);

}

/* We save all the filenames in the following array */

$files_to_upload = array();

/* Open the local directory form where you want to upload the files */

if ($handle = opendir($local_directory))

{

/* This is the correct way to loop over the directory. */

while (false !== ($file = readdir($handle)))

{

     if ($file != “.” && $file != “..”)

     {

            $files_to_upload[] = $file;

     }

}

    closedir($handle);

}

if(!empty($files_to_upload))

{

/* Now upload all the files to the remote server */

    foreach($files_to_upload as $file)

{

       /* Upload the local file to the remote server

             put(‘remote file’, ‘local file’);

        */

          $success = $sftp->put($remote_directory . $file,

                            $local_directory . $file,

                                 NET_SFTP_LOCAL_FILE);

}

}

?> 

Final Words

That’s it! We explained how to upload image files in a simple and more user-friendly way using AJAX and jQuery. It is easy to upload any file, including PDFs, through form data without refreshing the page using PHP, jQuery, MySQL, and Ajax. You can use our codes for image uploading without page reload.

Asma Khalid is a Product Manager at CloudPages. She also oversees Content Writing and Social Media at CloudPages.

Recent Posts

Get Newsletter Updates

10 Most Common WordPress Errors and How to Fix Them

10 Most Common WordPress Errors and How to Fix Them

‘Oops! WordPress dashboard does not work correctly due to unforeseen errors.’ Your smooth and happy day can quickly turn into confusion when you open your WordPress and see this message appear on your screen. It can be pretty frustrating, especially if it is your...

read more
MySQL Performance Tuning Tips For Better Database Optimization

MySQL Performance Tuning Tips For Better Database Optimization

Though MySQL is considered one of the most popular database managers, it still needs to be optimised every once in a while. On the other hand, when we talk about complex and big data sets, you need to optimise for high performance regularly. MySQL performance tuning...

read more
How to Join Two Tables in MySQL

How to Join Two Tables in MySQL

To give appropriate content for a WordPress website, MySQL stores data in tables. Irrespective of the prefix, each MySQL database table comprises columns and rows. The columns identify the data type, whereas the rows carry the actual data. In this article, we will...

read more
A Comprehensive Guide to WooCommerce Shortcodes

A Comprehensive Guide to WooCommerce Shortcodes

Ever heard of the term WooCommerce shortcodes? If not, don’t worry as you are not the only one on the bus. Interestingly, many people are unaware of WooCommerce WP eCommerce short codes, even those who have owned and run their WooCommerce store for a long time....

read more

Comments

0 Comments

Submit a Comment

Your email address will not be published.

Subscribe

Join Our Newsletter

Pin It on Pinterest

Share This