Display dynamic dropdown list – PHP

In this tutorial, we will be creating a dynamic dropdown to display list of orders. On selecting order from list, we display all product’s code in that order. And on selecting the product code, it will display the product’s detail.

We will be using a sample database named classicmodels, it is attached in the source files below. You can also download it from here.

Populate first dropdown

Create a file named index.php and create an empty <select> tag with a unique ID. We will be populating orders list in this dropdown.

<p>Orders</p>
<select id="orders">
    
</select>

Now create a function to populate all orders in this dropdown and call that function as soon as the page loads. We will be using pure Javascript in this tutorial, no jQuery is required.

<script type="text/javascript">
    function getOrders() {
        // Creating an AJAX object
        var ajax = new XMLHttpRequest();

        // A separate file is created to get orders list
        ajax.open("GET", "get-orders.php", true);

        // Actually sending the request to get data
        ajax.send();

        // Callback when request status changes
        ajax.onreadystatechange = function () {

            // readyState = 4, when the response is received
            // status = 200, when the request is successfull
            if (this.readyState == 4 && this.status == 200) {

                // this.responseText will be JSON string, so we are converting it in Javascript object
                // using function JSON.parse 
                var response = JSON.parse(this.responseText);

                // html variable will contain all list items as String
                var html = "<option>Select order</option>";

                for (var a = 0; a < response.length; a++) {
                    // Value attribute will be used to get order details
                    html += "<option value='" + response[a].orderNumber + "'>";

                        // This will be displayed to users
                        html += response[a].orderNumber;
                    html += "</option>";
                }

                // Adding items in <select> tag
                document.getElementById("orders").innerHTML = html;
            }
        };
    }

    // Calling the above created function when page loads.
    getOrders();
</script>

Now go ahead and create a file named get-orders.php and in this file, simply get all the orders from database table orders and return as JSON.

<?php

$connection = mysqli_connect("localhost", "root", "", "classicmodels");

$sql = "SELECT * FROM orders";
$result = mysqli_query($connection, $sql);

$data = array();

while ($row = mysqli_fetch_object($result))
    array_push($data, $row);

echo json_encode($data);

At this point, you will be able to see a list of orders in your first dropdown. The next step is to get all product’s code when user select any order from this list.

Populate second dropdown based on first value

First, attach an event that will be called when the user select any item from order’s list. Notice it is sending this.value which means user selected order number:

<p>Orders</p>
<select id="orders" onchange="getDetail(this.value);">
    
</select>

Now create a function to get all product’s code that have the same orderNumber as user has selected. Notice that we are sending orderNumber as parameter so we can get the record of only that order number:

function getDetail(orderNumber) {
    var ajax = new XMLHttpRequest();
    ajax.open("GET", "get-order-detail.php?orderNumber=" + orderNumber, true);
    ajax.send();

    ajax.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var response = JSON.parse(this.responseText);
            var html = "<option>Select product code</option>";
            for (var a = 0; a < response.length; a++) {
                html += "<option value='" + response[a].productCode + "'>";
                    html += response[a].productCode;
                html += "</option>";
            }
            document.getElementById("order-details").innerHTML = html;
        }
    };
}

Now, go ahead and create a file named get-order-detail.php and in this file, we will be getting records of only user selected order.

<?php

$orderNumber = $_GET["orderNumber"];
$connection = mysqli_connect("localhost", "root", "", "classicmodels");

$sql = "SELECT * FROM orderdetails WHERE orderNumber='$orderNumber'";
$result = mysqli_query($connection, $sql);

$data = array();

while ($row = mysqli_fetch_object($result))
    array_push($data, $row);

echo json_encode($data);

Now you will be able to see the values in 2nd dropdown as soon as you select some value from first dropdown. So we can say that our 2nd dropdown list is now dynamic. Because its value changes with respective to the 1st dropdown.

Browse our more free PHP tutorials.

[wpdm_package id=’127′]

View detail of user selected record – PHP

In this article, we will teach you how you can view detail of user selected record in PHP. We will display detail in Bootstrap modal.

For example, you are displaying a list of users or products or anything that has so much attributes that you cannot display them all in 1 table. That is where you will display only 2 or 3 attributes in a table and display every other detail in a pop-up.

Start off, by creating a simple index.php, it is the only file where we will be working on. You can download bootstrap library from the link below and paste them in your project directory, all files have also being attached in the source files at the end of this page (along with jQuery):

Download Bootstrap

Displaying records from database

First you have to display 2 or 3 attributes of records from database and create a button to view details. We will be using a sample database called classicmodels, you can find it in the source files below. And we will be displaying records from table named customers.

<?php
    // Connecting with database and executing query
    $connection = mysqli_connect("localhost", "root", "", "classicmodels");
    $sql = "SELECT * FROM customers";
    $result = mysqli_query($connection, $sql);
?>

<!-- Include bootstrap & jQuery -->
<link rel="stylesheet" href="bootstrap.css" />
<script src="jquery-3.3.1.min.js"></script>
<script src="bootstrap.js"></script>

<!-- Creating table heading -->
<div class="container">
    <table class="table">
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Phone</th>
        </tr>

        <!-- Display dynamic records from database -->
        <?php while ($row = mysqli_fetch_object($result)) { ?>
            <tr>
                <td><?php echo $row->customerNumber; ?></td>
                <td><?php echo $row->customerName; ?></td>
                <td><?php echo $row->phone; ?></td>
            </tr>
        <?php } ?>
    </table>
</div>

At this point, you will be able to view the records from database in a table. Now, you have to create a button which upon clicking will show the detail of that particular record. Change the following line in the table tag:

<tr>
    <th>ID</th>
    <th>Name</th>
    <th>Phone</th>
    <th>Actions</th>
</tr>

<?php while ($row = mysqli_fetch_object($result)) { ?>
    <tr>
        <td><?php echo $row->customerNumber; ?></td>
        <td><?php echo $row->customerName; ?></td>
        <td><?php echo $row->phone; ?></td>
        <!--Button to display details -->
        <td>
            <button class = "btn btn-primary">
                Details
            </button>
        </td>
    </tr>
<?php } ?>

Creating a pop-up/dialog to view details

Now, create a simple model.

<!-- Modal -->
<div class = "modal fade" id = "myModal" tabindex = "-1" role = "dialog" aria-hidden = "true">
   
   <div class = "modal-dialog">
      <div class = "modal-content">
         
         <div class = "modal-header">
            <h4 class = "modal-title">
               Customer Detail
            </h4>

            <button type = "button" class = "close" data-dismiss = "modal" aria-hidden = "true">
               ×
            </button>
         </div>
         
         <div id = "modal-body">
            Press ESC button to exit.
         </div>
         
         <div class = "modal-footer">
            <button type = "button" class = "btn btn-default" data-dismiss = "modal">
               OK
            </button>
         </div>
         
      </div><!-- /.modal-content -->
   </div><!-- /.modal-dialog -->
   
</div><!-- /.modal -->

Then create a function to be called when the button is pressed. We will load that customer’s data and display in this modal/pop-up.

<button class = "btn btn-primary" onclick="loadData(this.getAttribute('data-id'));" data-id="<?php echo $row->customerNumber; ?>">
    Details
</button>
  • We have created a custom attribute named data-id and assigned it the value of customer ID, we will be using this to get all record.
  • onclick event will call the function loadData and we are passing current customer ID as a parameter this.getAttribute(‘data-id’). This will get the value of data-id attribute in this button tag.

After that, you have to create a function and call an AJAX to get that customer’s data. We are using POST method, url will be same as current file name. In data object, we will be using get_data to check when user has requested to view the detail:

<script>
    function loadData(id) {
    	$.ajax({
    	    url: "index.php",
    	    method: "POST",
    	    data: {get_data: 1, id: id},
    	    success: function (response) {
    	        console.log(response);
    	    }
        });
    }
</script>

Now, at the start of this file index.php, get the ID of customer and provide the customer’s detail:

<?php
    // Check if user has requested to get detail
    if (isset($_POST["get_data"]))
    {
        // Get the ID of customer user has selected
        $id = $_POST["id"];

        // Connecting with database
        $connection = mysqli_connect("localhost", "root", "", "classicmodels");

        // Getting specific customer's detail
        $sql = "SELECT * FROM customers WHERE customerNumber='$id'";
        $result = mysqli_query($connection, $sql);
        $row = mysqli_fetch_object($result);

        // Important to echo the record in JSON format
        echo json_encode($row);

        // Important to stop further executing the script on AJAX by following line
        exit();
    }
?>

At this point, click on any customer’s detail button and in your browser console you will see it’s detail in JSON(string) format.

View detail of user selected record

Convert this JSON data in Javascript object on your AJAX success function. You will also need to create a custom HTML layout like in the following:

success: function (response) {
    response = JSON.parse(response);
    console.log(response);

    var html = "";

    // Displaying city
    html += "<div class='row'>";
        html += "<div class='col-md-6'>City</div>";
        html += "<div class='col-md-6'>" + response.city + "</div>";
    html += "</div>";

    // And now assign this HTML layout in pop-up body
    $("#modal-body").html(html);

    // And finally you can this function to show the pop-up/dialog
    $("#myModal").modal();
}

I have displayed only city name, try displaying every other column in the table too. That’s how you can view the detail of user selected record in PHP.

Learn more Javascript tutorials.

[wpdm_package id=’125′]

Calculate difference between 2 dates – jQuery

Demo – Calculate difference between 2 dates

Convert time to different timezones

Calculating difference between 2 dates requires 2 calendars to pick dates or you may want to calculate difference based on some database values. For example, say you have a project management site and when you create a project you also set it’s deadline too. Now you may want to know how many days are remaining till deadline, you will something like this:

$remaining_days = $deadline – $today;

So we will be using 2 different methods to calculate difference. 1st is by creating two input fields for the user to select the dates and 2nd method is by calculating difference from database datetime value.

From datetime picker

Start off by downloading the datetimepicker from the link below, you can also find this too in the source files at the end of this page:

Download datetimepicker

Download this library and place 3 files in your project:

  1. jquery.js
  2. build/jquery.datetimepicker.min.css
  3. build/jquery.datetimepicker.full.js

After that, include these files in your project, make sure to include jquery.js first:

<link rel="stylesheet" href="jquery.datetimepicker.min.css" />
<script src="jquery.js"></script>
<script src="jquery.datetimepicker.full.js"></script>

Now, create 2 input fields to select the dates and a button to click and calculate the difference:

<input type="text" id="date1" />
<input type="text" id="date2" />

<button onclick="calculateDifference();">Calculate</button>

First, you have to initialize both input fields to show the calendar when clicked:

<script>
    $("#date1").datetimepicker({
        timepicker: false,
        format: "Y-m-d"
    });

    $("#date2").datetimepicker({
        timepicker: false,
        format: "Y-m-d"
    });
</script>

At this point, you will be able to select 2 dates from 2 input fields. Now you have to implement the calculateDifference() inside <script> tag to actually perform the difference:

function calculateDifference() {
    // Get both values from input field and convert them into Javascript Date object
    var date1 = new Date($("#date1").val());
    var date2 = new Date($("#date2").val());

    // Difference can be calculated by subtracting the first date timestamp from second date timestamp
    var timeDifference = date2.getTime() - date1.getTime();

    // Just for debugging purpose
    console.log(timeDifference);
}

At this point, when you click the button, you will be able to see the difference in timestamp in your browser console. You can open the browser console by right clicking in empty area and select “Inspect element”. The 2nd tab should be named “Console”.

Now you have to convert this timestamp in days. As the timestamp is in milliseconds, you first have to convert them in seconds, then in hours, then finally in days.

// There are 1000 milliseconds in 1 second
var milliSecondsInOneSecond = 1000;

// There are 3600 seconds in 1 hour
var secondsInOneHour = 3600;

// And we all know there are 24 hours in 1 day
var hoursInOneDay = 24;

We have to divide this timestamp by the product of these 3 variables:

var days = timeDifference / (milliSecondsInOneSecond * secondsInOneHour * hoursInOneDay);
console.log(days);

If you check your browser console now, you will be able to view the difference of your 2 selected dates in days.

From database MySQL value

We are using a sample database called classicmodels, it will be included in the source files at the end of this page. We have a table called orders and 2 columns requiredDate and shippedDate. Subtracting shipped date from required date to know how many days it will take to send the product.

$days = $requiredDate – $shippedDate;

First we have to connect with database and get the record:

<?php
    $connection = mysqli_connect("localhost", "root", "", "classicmodels");
    $sql = "SELECT * FROM orders WHERE orderNumber = '10100'";
    $result = mysqli_query($connection, $sql);
    $row = mysqli_fetch_object($result);
?>

Now you have to convert these 2 datetime values in timestamp by using the PHP built-in function strtotime(). Then you can apply the same formula as above to convert milliseconds to days.

// Converting both values in timestamp milliseconds
$date1 = strtotime($row->shippedDate);
$date2 = strtotime($row->requiredDate);

// Calculating the difference in milliseconds
$date_difference = $date2 - $date1;

// Converting milliseconds into days
$days = round($date_difference / (60 * 60 * 24));
echo $days;

[wpdm_package id=’122′]

Secure your website using CSRF PHP

Cross site request forgery (CSRF) is a form of attack where are person sends an unwanted action as if he is a logged in user. We can secure our website from CSRF attack in PHP.

A successful CSRF attack can result in access to unauthorized data. Changing passwords of other users and stealing browser cookies or session data.

CSRF attacks are typically conducted by sending an email or message on social media. As the victim is authenticated at that time, the attacker can easily sends a request to get the information. And the server responds as it is being requested by real user.

We will be creating 3 files “csrf.php” which contains all the login for CSRF protected. “form.php” which will be using to submit form in a secure way. And “submit.php” which will be receiving and validating the user input.

Start off by starting a session and creating a simple PHP class:

csrf.php

<?php
    session_start();
    class CSRF
    {
    	//
    }
?>

Then, create a method to generate a unique special token for authenticated user:

<?php
    session_start();
    class CSRF
    {
    	public static function create_token()
    	{
    	    // Generating a unique token
    	    $token = md5(time());

    	    // Saving the token in session
    	    $_SESSION["token"] = $token;

    	    // Creating a hidden input field with that unique input
    	    echo "<input type='hidden' name='csrf_token' value='" . $token . "' />";
    	}
    }
?>

Above function will be used to create a token, now create a function to validate the token:

public static function validate_token($token)
{
    //
}

First check if the token exists in session, if not then it is an attempt from attacker:

public static function validate_token($token)
{
    if (!isset($_SESSION["token"]))
    {
        return false;
    }
}

Second, you need to check if the $token matches with the one in the session, if not then it is an attempt from attacker:

if ($_SESSION["token"] != $token)
{
    return false;
}
return true;

At this point, your csrf.php file should be like this:

<?php
    session_start();
    class CSRF
    {
    	public static function create_token()
    	{
    	    // Generating a unique token
    	    $token = md5(time());

    	    // Saving the token in session
    	    $_SESSION["token"] = $token;

    	    // Creating a hidden input field with that unique input
    	    echo "<input type='hidden' name='csrf_token' value='" . $token . "' />";
    	}

    	public static function validate_token($token)
        {
            if (!isset($_SESSION["token"]))
            {
                return false;
            }

            if ($_SESSION["token"] != $token)
            {
                return false;
            }
            return true;
        }
    }
?>

Now in form.php, first you have to include the csrf.php file:

<?php
    require_once "csrf.php";
?>

Then create a simple form and add that csrf_token inside that form:

<form method='POST' action='submit.php'>
    <?php CSRF::create_token(); ?>
</form>

Below this CSRF token line inside the form, you can add all your form fields:

<form method='POST' action='submit.php'>
    <?php CSRF::create_token(); ?>
    <input type="text" name="first_name" placeholder="Enter first name" />
    <input type="submit">
    .......
</form>

When you submit the form, csrf_token field also being sent along with other data. We will be using that field to validate the request. Now, create a 3rd file named submit.php:

submit.php

<?php
    require_once "csrf.php";

    // Validating the request
    if (CSRF::validate_token($_POST["csrf_token"]))
    {
    	echo "Process";
    }
    else
    {
    	echo "Error";
    }
?>

Now, execute the form.php file and try to change the csrf_token field by inspect element, and you will see that it will disallow all unauthenticated requests from any other person.

Also learn, how you can prevent direct access to files using htaccess from here.

[wpdm_package id=’119′]

Create currency converter in PHP

In this article, we will be creating a simple currency converter in PHP. You just need to tell the source and target currency and the amount. You can check the demo as well.

Demo

We will be using a FREE api to convert any currency to anyother at the standard market rates. Market rates may differ on time, also it may take some hours for the API to update the rates if the currency goes up or down.

You just have to provide both currencies and the amount you want to convert, and it will be converted accordingly.

No external library has been used in this script.

We start off by creating a simple form to get the source and destination currency, and the amount he wants to convert. For example, if you want to convert 143 USD dollars to PKR:

  • Source currency = USD
  • Destination currency = PKR
  • Amount = 143

Simple !

We will be creating just 2 files:

  1. index.php to get user input.
  2. convert.php to do the conversion.
<form method="POST" action="convert.php">
    <input type="text" name="from" placeholder="From" /> <br />
    <input type="text" name="to" placeholder="To" /> <br />
    <input type="number" name="amount" placeholder="Amount" /> <br />
    <input type="submit" value="Convert" /> <br />
</form>

convert.php

In this file, first we have to get the user input and save it in separate variable:

<?php
    $from = $_POST["from"];
    $to = $_POST["to"];
    $amount = $_POST["amount"];
?>

Then, we have to call the PHP built-in curl function and pass these variables as parameters to do the conversion. The URL of API is:

https://free.currconv.com/api/v7/convert?q=USD_PKR&compact=ultra&apiKey={your_api_key}

Get API key

You just have to change the currency according to yours (from the variables) and it will return the standard rate of 1 unit. For example, right now, the above URL will return 135. It is the value of 1 USD in PKR currency.

$string = $from . "_" . $to;
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "https://free.currconv.com/api/v7/convert?q=" . $string . "&compact=ultra&apiKey={your_api_key}",
    CURLOPT_RETURNTRANSFER => 1
));
  • CURLOPT_RETURNTRANSFER this will return the output as string in curl_exec() function instead of outputting it directly.
  • $string variable is created separately because it will be re-used in the next step.

Execute the curl command:

$response = curl_exec($curl);
print_r($response);

At this point, when you fill the form and submit you will see something similar to the output:

{“USD_PKR”:141.590271}

This is the response in JSON format. You have to convert it to PHP objects and array format:

$response = curl_exec($curl);
$response = json_decode($response, true);
print_r($response);
  • 2nd parameter to json_encode() function is true, which make sure the string will be converted in PHP array.

Now, it will print something like this:

Array ( [USD_PKR] => 141.590271 )

This is the conversion rate of currency of 1 unit. You can get it’s value in a variable:

$rate = $response[$string];

And can find the total by multipying this with the number of dollars user entered:

$total = $rate * $amount;
print_r($total);

Now, you will be able to view the actual price after conversion. So your currency converter in PHP is ready. If you have any problem in following this, kindly do let us know.

[wpdm_package id=’114′]

Dynamic countdown timer in PHP

Convert time to different timezones

We will be creating a countdown timer in PHP based on some DateTime column value from MySQL database. These type of timers are used mostly in bidding/auction sites where you display a countdown timer till last bid. You can also show a countdown timer to special events too like countdown till new yeardeadline of project etc.

We will be using a third-party library called TimeCircles. You can download it from here. It is also included in the source files attached at the end of this tutorial.

We will be using a sample database called classicmodels, it will be included in the source files.

Start off by downloading the jQuery and TimeCircles libraries and copy the following files in your project:

  1. jquery-3.3.1.min.js
  2. Create a folder named TimeCircles and paste the following files in it:
  3. TimeCircles.css
  4. TimeCircles.js
<script src="jquery-3.3.1.min.js"></script>
<script src="TimeCircles/TimeCircles.js"></script>
<link rel="stylesheet" type="text/css" href="TimeCircles/TimeCircles.css">

Now execute your MySql query to get the datetime value to show the countdown timer:

<?php
    $connection = mysqli_connect("localhost", "root", "", "classicmodels");
    $sql = "SELECT * FROM orders WHERE orderNumber='10100'";
    $result = mysqli_query($connection, $sql);
    $row = mysqli_fetch_object($result);
?>

In this case, we are getting some delivery order time till arrival from our sample database.

Now, create a simple <div> give it a unique id attribute and give the datetime value to data-date attribute. The countdown will be displayed based on this attribute’s value.

<div data-date="<?php echo $row->requiredDate; ?>" id="count-down"></div>

The last step is to initialize the time using a simple jQuery function. Call the TimeCircles() function from this <div> object when the page is fully loaded.

<script>
    $(function () {
        $("#count-down").TimeCircles();
    });
</script>

That’s it, run your file, you will be able to see the countdown timer. Your complete code should look like this:

<script src="jquery-3.3.1.min.js"></script>
<script src="TimeCircles/TimeCircles.js"></script>
<link rel="stylesheet" type="text/css" href="TimeCircles/TimeCircles.css">

<?php
    $connection = mysqli_connect("localhost", "root", "", "classicmodels");
    $sql = "SELECT * FROM orders WHERE orderNumber='10100'";
    $result = mysqli_query($connection, $sql);
    $row = mysqli_fetch_object($result);
?>

<div data-date="<?php echo $row->requiredDate; ?>" id="count-down"></div>

<script>
    $(function () {
        $("#count-down").TimeCircles();
    });
</script>

2nd library SyoTimer

Now we need to show the countdown timer in PHP using 2nd library called SyoTimer. Its CSS and JS files can be downloaded from link below. We have created a folder where its files needs to be saved. First include these files in your <head> tag:

<script src="syotimer/jquery.syotimer.js"></script>
<link rel="stylesheet" href="syotimer/default.css">

Then creates its div where we will render the countdown timer for SyoTimer library:

<div id="simple_timer"></div>

We need to get the timestamp value in Javascript, we are receiving it in PHP from MySQL database but we need to get it in Javascript. Simplest way is to create an hidden input field and then get its value in Javascript using getElementById function:

<input type="hidden" id="timer_value" value="<?php echo $row->requiredDate; ?>">

Then in Javascript, first get its value using getElementById function. Then create a Date object using that value. And finally display the SyoTimer:

var timer_value = document.getElementById("timer_value").value;
var date = new Date(timer_value);

$('#simple_timer').syotimer({
	year: date.getFullYear(),
	month: date.getMonth() + 1,
	day: date.getDate(),
	hour: date.getHours(),
	minute: date.getMinutes(),
	seconds: date.getSeconds()
});

Run the code and now you will be able to see the 2nd countdown timer created using SyoTimer library.

3rd library PsgTimer

Same as we did for SyoTimer, we need to save its CSS and JS files in a separate folder. Then include those files in our <head> tag:

<script src="psgTimer/jquery.psgTimer.js"></script>
<link rel="stylesheet" href="psgTimer/psgTimer.css">

Then create a <div> tag where we will display the countdown timer:

<div id="psgTimer" data-label-days="Days"
    data-label-hours="Hours"
    data-label-minutes="Minutes"
    data-label-seconds="Seconds"></div>

And finally initialize that in Javascript:

new PsgTimer('#psgTimer', {
    endDateTime: date
});

Run the code and now you will be able to see the 3nd countdown timer created using PsgTimer library.

4th library ComingSoon

Now we are going to use another library for countdown timer know as ComingSoon, same as we did for previous libraries, we need to save its CSS and JS files in a separate folder. Then include those files in our <head> tag:

<script src="comingsoon/jquery.mb-comingsoon.js"></script>
<link rel="stylesheet" href="comingsoon/mb-comingsoon.css">

Create a <div> where this countdown timer will be displayed:

<div id="myCounter"></div>

And finally initialize that in our Javascript:

$('#myCounter').mbComingsoon({
	expiryDate: date,
	interval: 1000,
	speed: 500,
	localization: {
		days:"days",
		hours:"hours",
		minutes:"minutes",
		seconds:"seconds"
	},
	callBack: function () {
		console.log("ended");
	}
});

These are 4 libraries that we thought can be used in any type of website design. But if you are having issues integrating that in your project, feel free to post a comment in the comments section below. If you have any suggestion for another library, kindly let me know, I will try to add that in this tutorial too.

[wpdm_package id=’111′]

Create ZIP file with password – PHP

To create a ZIP file with password in PHP, there isn’t any need for third-party library. PHP provides a large variety of built-in functions to create a ZIP file. Also PHP has an in-built option for setting the password on ZIP files.

We will creating a simple script to allow user to upload multiple files, then will compress those files in ZIP and asking the password from user. And apply that password on that ZIP file.

We will be creating just 2 files, 1 for client (index.php) and 1 for server (upload.php). So, start off by creating a simple HTML form in file index.php:

Create form to select multiple files (index.php)

<form method="POST" enctype="multipart/form-data" action="upload.php">
</form>

enctype=”multipart/form-data” and method=”POST” are important in <form> tag to upload file.

<input type="file" name="files[]" required multiple />
<input type="submit" name="upload" />

multiple attribute will be used to allow user to select multiple files.

Upload, compress files to ZIP (upload.php)

<?php
    $zip = new ZipArchive();
?>

Creates a built-in ZipArchive class object and save it in variabled called $zip.

Call open() function from $zip object to create a new empty ZIP file in memory.

$zip->open("file.zip", ZIPARCHIVE::CREATE);
  • First parameter is the name of ZIP file you want to set.
  • Second is the action you want to perform, you can use OPEN, CREATE methods to read or write the file respectively.

As we are allowing user to select multiple files, we need to create a loop on user selected files:

for ($a = 0; $a < count($_FILES["files"]["name"]); $a++)
{
    //
}

Inside this loop, we have to get the content of each file separately:

$content = file_get_contents($_FILES["files"]["tmp_name"][$a]);

Then you have to call the addFromString() method on $zip object. It accepts 2 parameters, 1st is the name of file inside the ZIP archive, 2nd is the content of file. In this case, 2nd parameter is stored in variable called $content.

$zip->addFromString($_FILES["files"]["name"][$a], $content);

After the loop, we have to call the close() to free-up the space in memory.

$zip->close();

At this point, your index.php file will look like this:

<form method="POST" enctype="multipart/form-data" action="upload.php">
    <input type="file" name="files[]" required multiple />
    <input type="submit" name="upload" />
</form>

And your upload.php file will look like this:

<?php
    $zip = new ZipArchive();
    $zip->open("file.zip", ZIPARCHIVE::CREATE);
    for ($a = 0; $a < count($_FILES["files"]["name"]); $a++)
    {
        $content = file_get_contents($_FILES["files"]["tmp_name"][$a]);
        $zip->addFromString($_FILES["files"]["name"][$a], $content);
    }
    $zip->close();
?>

Applying password to archive (upload.php)

Create simple password input field in index.php file:

<input type="password" name="password" required />

And in upload.php file, after the open() method, call the setPassword() method and send user selected password as parameter:

$zip->setPassword($_POST["password"]);

And in loop, after addFromString() method, call setEncryptionName() method to apply password on each file in the ZIP:

$zip->setEncryptionName($_FILES["files"]["name"][$a], ZipArchive::EM_AES_256);
  • 1st parameter is the name of file.
  • 2nd parameter is the type of encryption algorithm used.

Below is the complete source code of both files:

index.php

<form method="POST" enctype="multipart/form-data" action="upload.php">
    <input type="file" name="files[]" required multiple />
    <input type="password" name="password" required />
    <input type="submit" name="upload" />
</form>

upload.php

<?php
    $zip = new ZipArchive();
    $zip->open("file.zip", ZIPARCHIVE::CREATE);
    $zip->setPassword($_POST["password"]);

    for ($a = 0; $a < count($_FILES["files"]["name"]); $a++)
    {
        $content = file_get_contents($_FILES["files"]["tmp_name"][$a]);
        $zip->addFromString($_FILES["files"]["name"][$a], $content);
        $zip->setEncryptionName($_FILES["files"]["name"][$a], ZipArchive::EM_AES_256);
    }
    $zip->close();
?>

Run the index.php file, upload some files and set the password. Your selected files will be archived to 1 and password will be applied.

If you want to ZIP your files and protect them with password in command line, follow here.

Right now, this only works for Mac OS X.

[wpdm_package id=’107′]

AJAX file upload with progress bar – Javascript, PHP

In this tutorial, we are going to show you how you can upload file with AJAX. We will also be displaying a progress bar. We will be using PHP.

AJAX file upload with progress bar

There are 2 types of progress bars, one with infinite progress loop similar to this:

and one which shows the number of percentage completed like this:

We will be using the 2nd progress bar as it is more accurate than the first one.

Select file

We will be using an AJAX function to upload user selected file on the server and show the progress bar of how much the file has been uploaded. We will be creating just 2 files, 1 for client (index.php) and 1 for server (upload.php). So, start off by creating a simple HTML form in file index.php:

<form method="POST" enctype="multipart/form-data" onsubmit="return onSubmit();">
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" />
</form>
  • enctype=”multipart/form-data” and method=”POST” are important in <form> tag to upload file.

Prevent form from submitting

In order to upload file via AJAX, first we need to stop the default form action method. We can do this by return false from onsubmit attribute of <form> tag. All the code written in this tutorial is pure Javascript, there is no dependency of jQuery in this tutorial.

<script>
    function onSubmit() {
        return false;
    }
</script>

Get input type file in Javascript

Now, you have to get the user selected file and save it in a variable called file. document.getElementById(“file”) helps in getting the input type file object and it has an array of user selected files in a variable called files.

function onSubmit() {
    var file = document.getElementById("file").files[0];
    return false;
}

Call AJAX to upload file

To call an AJAX to upload the file, first create an built-in XMLHttpRequest object and save in variable ajax. This object is supported in all browsers and it is native Javascript object, no jQuery is required.

var ajax = new XMLHttpRequest();

Now call open(method, url, async) function from ajax object.

  • First parameter is the method of request GET or POST.
  • Second is the name of PHP file which will upload the file. In this case upload.php which will be created in next step.
  • Third is a boolean, whether the request is asynchronous or not. true for asynchronous. Asynchronous requests does not hang up the browser. Syncronized requests may block the browser if the script at upload.php is very time-taking.
ajax.open("POST", "upload.php", true);

Sending file via AJAX required an FormData object to be appended in the AJAX request. We can create a FormData object simply by the following line:

var formData = new FormData();
formData.append("file", file);
  • formData.append 1st parameter is the string which will used in upload.php file to upload the file and 2nd parameter is the user selected file. In this case, it is stored in variable file

Call the send() function from ajax object to actually call an AJAX request. It accepts 1 parameter that is of FormData object.

ajax.send(formData);

When response is received from server

ajax object has multiple functions that are called once the status of request is changed. For example, when server receives the request, if server does not exists, if server failed to respond etc. All these callbacks are received in a function called onreadystatechange.

ajax.onreadystatechange = function() {
    //
};

Now we have to respond only if the request is successful. In this onreadystatechange function, we have 3 variables readyState, status and responseText.

  • readyState will have value 4 when the request is done/completed.
  • status will have value 200 when everything goes right.
ajax.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
    	console.log(this.responseText);
    }
};

Save file on server – PHP

Now create a new file named upload.php and open it in code editor. In this file, we will just be storing the file in a server. Paste the following code in upload.php file:

<?php
    move_uploaded_file($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]);
    echo "Done";
?>

At this point if you run the index.php file, you will be able to select a file and save it in your server and your index.php will look like this:

<form method="POST" enctype="multipart/form-data" onsubmit="return onSubmit();">
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" />
</form>

<script>
    function onSubmit() {
        var file = document.getElementById("file").files[0];

        var formData = new FormData();
        formData.append("file", file);
        
        var ajax = new XMLHttpRequest();
        ajax.open("POST", "upload.php", true);
        ajax.send(formData);

        ajax.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                console.log(this.responseText);
            }
        };

        return false;
    }
</script>

And your upload.php should look like this:

<?php
    move_uploaded_file($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]);
    echo "Done";
?>

Show progress bar

Now, in order to view the progress bar you can simply create an <progress> tag anywhere in your index.php where you want to see the progress. Provide it a unique id and set it’s initial value to 0:

<progress id="progress" value="0"></progress>

Get progress bar object in javascript, right above return false; line in the function onSubmit(), like this:

function onSubmit() {
    ..........

    ajax.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            console.log(this.responseText);
        }
    };

    var progress = document.getElementById("progress");
    return false;
}

While uploading files, ajax object also has an event called onprogress that will tell the current uploaded file percentage:

ajax.upload.onprogress = function (event) {
    //
};
  • event variable will tell the current status of uploaded file.

First you have to set the maximum value of progress object to that required by an AJAX request to upload the file:

progress.max = event.total;

Now simply set the progress value attribute to uploaded value from event object:

progress.value = event.loaded;

Now, you will be able to view the progress of an uploaded file via AJAX.

Complete code

Here is a complete code of your index.php file:

<form method="POST" enctype="multipart/form-data" onsubmit="return onSubmit();">
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" />
</form>

<progress id="progress" value="0"></progress>

<script>
    function onSubmit() {
        var file = document.getElementById("file").files[0];

        var formData = new FormData();
        formData.append("file", file);
        
        var ajax = new XMLHttpRequest();
        ajax.open("POST", "upload.php", true);
        ajax.send(formData);

        ajax.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                console.log(this.responseText);
            }
        };

        var progress = document.getElementById("progress");
        ajax.upload.onprogress = function (event) {
            progress.max = event.total;
            progress.value = event.loaded;
        };

        return false;
    }
</script>

Show progress of download with remaining time – Javascript

[wpdm_package id=’104′]

Get data from database using AJAX, Javascript, PHP, MySQL

By the end of this tutorial, you will be able to get data from database using AJAX using simple Javascript (no jQuery). Benefits of using AJAX are:

  1. Page loads faster as there will be no PHP script running during page load.
  2. If you want to change data, you can do that easily without having to refresh the page.
  3. You can show the same data on multiple pages, without having to rewrite the query. Just call the same javascript function.

Where AJAX is used ?

Google Earth

When you scroll in Google Earth, an AJAX request is sent to get the images of new location.

Facebook

When you scroll at the end of page in Facebook, an AJAX request is sent to get the older posts.

Charts & Graphs

In charts, when you change the date value, the charts has been updated to selected date via AJAX.

We are going to show records of employees from database table. We are using database named classicmodel, it will be included in the source files.

Create an HTML table

First we are going to create a file to show the data from database called index.php

Create a simple HTML table and give a unique ID to <tbody> tag

<table>
    <tr>
	<th>First name</th>
	<th>Last name</th>
	<th>Job title</th>
    </tr>

    <tbody id="data"></tbody>
</table>

Call AJAX to get data from database

To call an AJAX to get the data, first create an built-in XMLHttpRequest object and save in variable ajax.

<script>
    var ajax = new XMLHttpRequest();
</script>

Now call open(method, url, async) function from ajax object.

ajax.open("GET", "data.php", true);
  • First parameter is the method of request GET or POST.
  • Second is the name of file from where to get data. In this case data.php which will be created in next step.
  • Third is a boolean, whether the request is asynchronous or not. true for asynchronous. Asynchronous requests does not hang up the browser. Syncronized requests may block the browser if the script at data.php is very time-taking.

You can also send headers with your request using the following methods:

ajax.setRequestHeader("Accept", "application/json")
ajax.setRequestHeader("Authorization", "Bearer {token}")

You can pass as many headers as you want by calling the method setRequestHeader multiple times.

Call the send() function from ajax object to actually call an AJAX request. It accepts no parameter.

ajax.send();

ajax object has multiple functions that are called once the status of request is changed. For example, when server receives the request, if server does not exists, if server failed to respond etc. All these callbacks are received in a function called onreadystatechange.

ajax.onreadystatechange = function() {
    //
};

Now we have to respond only if the request is successful. In this onreadystatechange function, we have 3 variables readyState, status and responseText.

  • readyState will have value 4 when the request is done/completed.
  • status will have value 200 when everything goes right.
ajax.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
    	console.log(this.responseText);
    }
};

Get data from MySQL database using PHP

Now create a new file named data.php and open it in code editor. First, you have to connect with database:

<?php
$conn = mysqli_connect("localhost", "root", "", "classicmodels");
  • root is the name of database user.
  • Third parameter is the password of database. For XAMPP/WAMP, it will be an empty string.
  • classicmodels is the name of database.

Now, write your query to get the records from database. In my case, I am just getting all employees from database table named employees:

$result = mysqli_query($conn, "SELECT * FROM employees");

Create an array and loop through all database records returned from previous query, and save those records in that array:

$data = array();
while ($row = mysqli_fetch_object($result))
{
    array_push($data, $row);
}

Now, whatever you echo will returned to the AJAX callback function in index.php file. In case of an array, you have to convert the array into JSON format and then echo it.

echo json_encode($data);
exit();
  1. exit(); will prevent the code from further executing.

    At this point, if you run the index.php file, you will see similar to the following in your browser console:

Now, go back to index.php file and convert this JSON string back into an array:

ajax.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
    	console.log(this.responseText);
    	var data = JSON.parse(this.responseText);
    	console.log(data);
    }
};

JSON string should now be converted into an Javascript object named data.If you run index.php now and see the browser console, you will see something similar to the following:

json-to-object

Show data in HTML table

You got the data, now you just have to append it in table. Create an empty string variable named html:

var html = "";

Loop through all employees list:

for(var a = 0; a < data.length; a++) {
    //
}

Inside the loop, append the data in html variable:

for(var a = 0; a < data.length; a++) {
    var firstName = data[a].firstName;
    var lastName = data[a].lastName;
    var jobTitle = data[a].jobTitle;

    html += "<tr>";
        html += "<td>" + firstName + "</td>";
        html += "<td>" + lastName + "</td>";
        html += "<td>" + jobTitle + "</td>";
    html += "</tr>";
}

After the loop, append the html variable in <tbody> tag:

document.getElementById("data").innerHTML += html;

Now, your index.php file should look like this:

<table>
    <tr>
	<th>First name</th>
	<th>Last name</th>
	<th>Job title</th>
    </tr>

    <tbody id="data"></tbody>
</table>

<script>
    var ajax = new XMLHttpRequest();
    ajax.open("GET", "data.php", true);
    ajax.send();

    ajax.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var data = JSON.parse(this.responseText);
            console.log(data);

            var html = "";
            for(var a = 0; a < data.length; a++) {
                var firstName = data[a].firstName;
                var lastName = data[a].lastName;
                var jobTitle = data[a].jobTitle;

                html += "<tr>";
                    html += "<td>" + firstName + "</td>";
                    html += "<td>" + lastName + "</td>";
                    html += "<td>" + jobTitle + "</td>";
                html += "</tr>";
            }
            document.getElementById("data").innerHTML += html;
        }
    };
</script>

And your data.php file should be like this:

<?php
$conn = mysqli_connect("localhost", "root", "", "classicmodels");
$result = mysqli_query($conn, "SELECT * FROM employees");

$data = array();
while ($row = mysqli_fetch_object($result))
{
    array_push($data, $row);
}

echo json_encode($data);
exit();

Run the index.php file and you will see your data will be displayed via AJAX. So that’s how you can get data from the database using AJAX and display it in an HTML table.

There is more

This is just to get the data from the database. Follow this tutorial to learn complete CRUD (Create, Read, Update and Delete) operation in AJAX.

[wpdm_package id=’93’]

How to resize an image without stretching – PHP

In order to resize an image without stretching, we will be calling built-in functions of PHP. No third party library will be used in this tutorial.

Resizing an image without stretching involves setting the new dimension of an image. You cannot decide both (width & height) of an image in order to resize without stretching. You will only tell the new dimension and this script will resize the image by maintaining its aspect ratio.

Get image and dimension

<form method="POST" action="resize.php" enctype="multipart/form-data">
    <p>
        <input type="file" name="file" onchange="onFileSelected();" id="image" accept="image/*" required="">
    </p>

    <p>
        <input type="number" name="enter_dimension" required="">
    </p>
    <input type="submit" name="submit">
</form>
  • enctype=”multipart/form-data” and method=”POST” are important in <form> tag
  • accept=”image/*” in <img> tag will allow you to view only images. Other documents will automatically be hidden.
  • onchange=”onFileSelected();” in <img> tag will be used to view the image before resizing (just for confirmation)

Show image preview

<img src="" id="preview">

<script type="text/javascript">
function onFileSelected() {
    var image = document.getElementById("image").files;
    if (image.length == 0) {
        console.log("Please select an image");
        return;
    }
    image = image[0];

    var reader = new FileReader();
    reader.onload = function (e) {
        document.getElementById('preview').setAttribute('src', e.target.result);
    }
    reader.readAsDataURL(image);
}
</script>

At this point, you will have something similar to the following:

Resizing image

Create a new file named “resize.php” (or it should be same as <form> tag action=”” attribute in step 1). First, you have to get the input dimension and user selected image:

<?php                        
$dimension = $_POST["enter_dimension"];                    
$file_name = $_FILES["file"]["tmp_name"];
    
$image_size = getimagesize($file_name);                        
$width = $image_size[0];    
$height = $image_size[1];
            
$ratio = $width / $height;                        
if ($ratio > 1)            
{
    $new_width = $dimension;
    $new_height = $dimension / $ratio;            
}            
else                        
{
    $new_height = $dimension;                    
    $new_width = $dimension * $ratio;            
}
                        
$src = imagecreatefromstring(file_get_contents($file_name));                        
$destination = imagecreatetruecolor($new_width, $new_height);

imagecopyresampled($destination, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height);                        
imagepng($destination, $file_name);
        
imagedestroy($src);                        
imagedestroy($destination);
            
move_uploaded_file($file_name, $_FILES["file"]["name"]);                        
echo "<img src='" . $_FILES["file"]["name"] . "' />";

Explanation

  • getimagesize: This function returns an array containing the width and height of the image.
  • imagecreatefromstring: It creates a new image from image file data.
  • imagecreatetruecolor: It just accepts width and heigth as parameters. And return the true color of the image.
  • imagecopyresampled: This function copies the image from source to destination. And also resize the image with provided width and height.
  • imagepng: This outputs the PNG image to the browser if the 2nd parameter is not provided. But since we provided the 2nd parameter, so it will save the image in a separate PNG file.
  • imagedestroy: Simply destroys the image object.

[wpdm_package id=’81’]