Load more data using AJAX – PHP

Learn how you can show a “Load more” button using AJAX, PHP and MySQL. No external library has been used in this tutorial.

What is “Load more” button ?

By “Load more” we mean creating a button that allows you to show only 10 or 20 records and on clicking that button will fetch next 10 records from database without having to refresh the page. This function is heavily used in tech giant Facebook where older posts are fetched by scrolling without refreshing the page.

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

Create layout

We will be using employees table and displaying employeeNumber, firstName, lastName and email fields. A unique ID should be provided to <tbody> which will be used to append data using Ajax.

<table>
    <thead>
        <tr>
            <th>Number</th>
            <th>First name</th>
            <th>Last name</th>
            <th>Email</th>
        </tr>
    </thead>

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

<button type="button" onclick="getData();">
    Load More
</button>

Display initial records

We are displaying 10 records in each step and we will need just 1 variable for this. start to tell the starting position of fetching data and it will be incremented in each step.

<script>
    // Starting position to get new records
    var start = 0;

    // This function will be called every time a button pressed 
    function getData() {
        // Creating a built-in AJAX object
        var ajax = new XMLHttpRequest();

        // Sending starting position
        ajax.open("GET", "Http.php?start=" + start, true);

        // Actually sending the request
        ajax.send();

        // Detecting request state change
        ajax.onreadystatechange = function () {

            // Called when the response is successfully received
            if (this.readyState == 4 && this.status == 200) {

                // For debugging purpose only
                console.log(this.responseText);
            }
        };
    }

    // Calling the function on page load
    getData();
</script>

At this point if you run the program, you will see an empty table and a button, now you need to create Http.php file to handle each request.

Handling AJAX request – PHP

Create a new file and name it Http.php, in this file we will simply get the offset (start variable) and display the records based on that value.

<?php

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

// Getting offset to show next records
$start = $_GET["start"];

// Executing the query based on $start variable
$sql = "SELECT * FROM employees LIMIT $start, 10";
$result = mysqli_query($connection, $sql);

// Storing all returned records in an array
$data = array();
while ($row = mysqli_fetch_object($result))
    array_push($data, $row);

// Sending response back to AJAX
echo json_encode($data);

Now if you view your browser console, you will see some JSON string data when the page loads.

Appending records in table

Now you need to convert that JSON string into Javascript array and append in <tbody> tag. Paste the following code back in your index.php file:

ajax.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        console.log(this.responseText);
        
        // Converting JSON string to Javasript array
        var data = JSON.parse(this.responseText);
        var html = "";

        // Appending all returned data in a variable called html
        for (var a = 0; a < data.length; a++) {
            html += "<tr>";
                html += "<td>" + data[a].employeeNumber + "</td>";
                html += "<td>" + data[a].firstName + "</td>";
                html += "<td>" + data[a].lastName + "</td>";
                html += "<td>" + data[a].email + "</td>";
            html += "</tr>";
        }

        // Appending the data below old data in <tbody> tag
        document.getElementById("data").innerHTML += html;

        // Incrementing the offset so you can get next records when that button is clicked
        start = start + 10;
    }
};

So for example, first time you will get employees from 1 to 10 and next time you hit load more button you will get employees from 11 to 20 and so on.

That’s how you can show a “Load more” button using AJAX, PHP and MySQL. You can also create a load more button in Node JS and Mongo DB. Learn from here how you can do that.

[wpdm_package id=’138′]

Reset password – PHP & MySQL

We will be using 4 files to implement reset password option.

  • index.php (to get email address)
  • send-recovery-mail.php (to send email)
  • reset-password.php (to enter new password)
  • new-password.php (to update the password)

Your table structure should be like this:

You need to create a table in database called users and the most important columns are email and reset_token. Sending email via localhost requires an Gmail account and you need to enable less secure apps for your account. You can enable it from the link below:

Enable less secure apps

Enter email address

Create a simple form to get user’s email address, where recovery mail should be sent.

<form method="POST" action="send-recovery-mail.php">
    <input type="email" name="email">
    <input type="submit" value="Send recovery email">
</form>

Send recovery email

We will be using PHPMailer library, you can download it from the link below:

Download PHPMailer

Next you need to include the library and make a connection with database:

<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

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

First you need to check if a user of that email exists in your database:

$email = $_POST["email"];

$sql = "SELECT * FROM users WHERE email = '$email'";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0)
{
    //
}
else
{
    echo "Email does not exists";
}

Inside the if statement, you need to generate a unique token which will be sent in email:

if (mysqli_num_rows($result) > 0)
{
    $reset_token = time() . md5($email);
}
else
{
    echo "Email does not exists";
}

After that, you need to save this token against that user’s database record:

$sql = "UPDATE users SET reset_token='$reset_token' WHERE email='$email'";
mysqli_query($connection, $sql);

Then you create a variable called $message and write all the text that you want to send in recovery email:

$message = "<p>Please click the link below to reset your password</p>";
$message .= "<a href='http://localhost/tutorials/add-a-reset-password-option/reset-password.php?email=$email&reset_token=$reset_token'>";
	$message .= "Reset password";
$message .= "</a>";
  • Replace your web URL with the highlighted text.

Now, simply send the email via PHPMailer. We have created a separate function to do that:

function send_mail($to, $subject, $message)
{
    $mail = new PHPMailer(true);

    try {
        //Server settings
	$mail->SMTPDebug = 0;                                       // Enable verbose debug output
	$mail->isSMTP();                                            // Set mailer to use SMTP
	$mail->Host       = 'smtp.gmail.com;';  // Specify main and backup SMTP servers
	$mail->SMTPAuth   = true;                                   // Enable SMTP authentication
	$mail->Username   = 'your_gmail_address';                     // SMTP username
	$mail->Password   = 'your_gmail_password';                               // SMTP password
	$mail->SMTPSecure = 'tls';                                  // Enable TLS encryption, `ssl` also accepted
	$mail->Port       = 587;                                    // TCP port to connect to

	$mail->setFrom('your_gmail_address', 'your_name');
	//Recipients
	$mail->addAddress($to);

	// Content
	$mail->isHTML(true);                                  // Set email format to HTML
	$mail->Subject = $subject;
	$mail->Body    = $message;

	$mail->send();
	echo 'Message has been sent';
    } catch (Exception $e) {
	echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    }
}

And you can call this function right after$message variable:

send_mail($email, "Reset password", $message);

At this point, when you enter email and hit submit you will receive an email with a receovery link. On clicking you will be redirected to your site on page reset-password.php.

Enter new password

Now you need to create a file named reset-password.php. In this file, first you need to check if it comes from email link:

<?php

$email = $_GET["email"];
$reset_token = $_GET["reset_token"];

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

$sql = "SELECT * FROM users WHERE email = '$email'";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0)
{
    //
}
else
{
    echo "Email does not exists";
}

Second, you need to check if the token is not tempered, so that you cannot change someone else’s password:

$user = mysqli_fetch_object($result);
if ($user->reset_token == $reset_token)
{
    //
}
else
{
    echo "Recovery email has been expired";
}

Third, display a simple form to enter new password. The email and reset_token needs to be hidden in this file so that you can update password for only that specific user:

if ($user->reset_token == $reset_token)
{
    ?>
    <form method="POST" action="new-password.php">
        <input type="hidden" name="email" value="<?php echo $email; ?>">
    	<input type="hidden" name="reset_token" value="<?php echo $reset_token; ?>">
		
    	<input type="password" name="new_password" placeholder="Enter new password">
    	<input type="submit" value="Change password">
    </form>
    <?php
}
else
{
    echo "Recovery email has been expired";
}

Reset the password

Now you only needs to create a new file named new-password.php and paste the following code in it:

<?php

$email = $_POST["email"];
$reset_token = $_POST["reset_token"];
$new_password = $_POST["new_password"];

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

$sql = "SELECT * FROM users WHERE email = '$email'";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0)
{
    $user = mysqli_fetch_object($result);
    if ($user->reset_token == $reset_token)
    {
    	$sql = "UPDATE users SET password='$new_password' WHERE email='$email' AND reset_token='$reset_token'";
    	mysqli_query($connection, $sql);

    	echo "Password has been changed";
    }
    else
    {
    	echo "Recovery email has been expired";
    }
}
else
{
    echo "Email does not exists";
}

That’s how you can reset password using PHP and MySQL. Learn also how you can do email verification in your website.

[wpdm_package id=’136′]

Attach files in email – PHP

In this tutorial, we will teach you how you can attach files in an email using PHP. We will be using PHPMailer library to send an email.

Attach files in email – PHP

We will be creating a simple form to enter email address of receiver, subject, message and ability to select a file. That file will be attached in a email and sent to the receiver. If you are testing via XAMPP/WAMP/MAMP you may need to download PHPMailer library from the link below:

Download PHPMailer

You can install the library from composer, all details are provided in the link above. We will be using 2 files, 1 to display a form for input and 2nd to send the mail.

Getting user input

Below is the code for index.php file

<form method="POST" enctype="multipart/form-data" action="send-mail.php">
    <p>
	Send to:
	<input type="text" name="receiver">
    </p>

    <p>
	Subject:
	<input type="text" name="subject">
    </p>

    <p>
	Message:
	<textarea name="message"></textarea>
    </p>

    <p>
	Select file:
	<input type="file" name="file">
    </p>

    <input type="submit">
</form>

Attaching file with email

Sending email via localhost requires an Gmail account and you need to enable less secure apps for your account. You can enable it from the link below:

Enable less secure apps

Now paste the following code in your send-mail.php file:

<?php

// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Load Composer's autoloader
require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = 0;                                       // Enable verbose debug output
    $mail->isSMTP();                                            // Set mailer to use SMTP
    $mail->Host       = 'smtp.gmail.com;';  // Specify main and backup SMTP servers
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = 'your_gmail_ID';                     // Your gmail address
    $mail->Password   = 'your_gmail_password';                               // Your gmail password
    $mail->SMTPSecure = 'tls';                                  // Enable TLS encryption, `ssl` also accepted
    $mail->Port       = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('your_gmail_ID', 'your_name');
    $mail->addAddress($_POST["receiver"]);

    $file_name = $_FILES["file"]["name"];
    move_uploaded_file($_FILES["file"]["tmp_name"], $file_name);
    $mail->addAttachment($file_name);

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = $_POST["subject"];
    $mail->Body    = $_POST["message"];

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

If you are using Mac, you may need to enable folder permission. You can enable folder permission by following steps below:

Folder permission for Mac users
Folder permission for Mac users

Now go ahead and try to submit the form and attaching any file to it. You will have attached file in your inbox (or in your spam if using localhost).

Instead of attaching the file in email, you can also upload the file on your server. And share its download link via an email. Learn here how you can do that.

[wpdm_package id=’133′]

Upload, Download and Delete files – PHP

We will teach you how you can upload, download and delete files in PHP. We will be implementing 3 functions and will be creating 3 files for each function:

  1. upload.php for uploading the file
  2. index.php for downloading the file
  3. delete.php for deleting the file

Upload file

Start off, by creating 2 files index.php and upload.php, also create a folder named uploads all uploaded files will be stored in this folder. If you are using Mac, you may need to enable permission by following the below steps:

Folder permission for Mac users

Folder permission for Mac users

Now you need to create a simple form that allows a user to select file from his computer to upload in your server:

<form method="POST" action="upload.php" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="Upload">
</form>

Next create a file named upload.php and paste the following code in it:

<?php

// Getting uploaded file
$file = $_FILES["file"];

// Uploading in "uplaods" folder
move_uploaded_file($file["tmp_name"], "uploads/" . $file["name"]);

// Redirecting back
header("Location: " . $_SERVER["HTTP_REFERER"]);

At this point, if you execute the index.php file you will be able to select file and when you click Upload button, the selected file should be saved in uploads folder.

Download file

In order to download the file, we are going to display a list of all files and a Download button. Paste the following code in index.php file:

<?php

// This will return all files in that folder
$files = scandir("uploads");

// If you are using windows, first 2 indexes are "." and "..",
// if you are using Mac, you may need to start the loop from 3,
// because the 3rd index in Mac is ".DS_Store" (auto-generated file by Mac)
for ($a = 2; $a < count($files); $a++)
{
    ?>
    <p>
    	<!-- Displaying file name !-->
        <?php echo $files[$a]; ?>

        <!-- href should be complete file path !-->
        <!-- download attribute should be the name after it downloads !-->
        <a href="uploads/<?php echo $files[$a]; ?>" download="<?php echo $files[$a]; ?>">
            Download
        </a>
    </p>
    <?php
}

At this point, if you refresh index.php you will see a list of all your uploaded files along with a Download button. Clicking on the Download button, will open a Download dialog based on your browser.

Delete file

In order to delete the file, first display a button to be clicked to delete. Href should be the full path of the file. The following code should be inserted inside the loop, after the Download button:

<a href="delete.php?name=uploads/<?php echo $files[$a]; ?>" style="color: red;">
    Delete
</a>

Create a new file named delete.php and paste the following code in it:

<?php

// Built-in PHP function to delete file
unlink($_GET["name"]);

// Redirecting back
header("Location: " . $_SERVER["HTTP_REFERER"]);

Now you will see a red button with a text Delete, on click it will delete the file and refresh the index.php page so you will see the remaining files. That’s how you can upload, download and delete the files in PHP.

You can also learn to:

  1. Upload file in Node JS
  2. Download files in BLOB
  3. Upload, download, and delete from Firebase storage from here

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′]