Add dynamic rows in React

In this tutorial, you will learn how to add dynamic rows in React. If you want to do it in plain HTML (without using React), then you can follow this.

First, you need to create an array that will hold all the rows you want to display.

const [data, setData] = React.useState([]);

After that, you need to create a button that when clicked will add a new element in array.

<button type="button" onClick={ function () {
    const temp = [ ...data ];
    temp.push({
        name: "",
        age: ""
    });
    setData(temp);
} }>Add row</button>

In order to push a new element in array in React state variable, we first need to create a shallow copy of it. We can also do a deep copy, but for simple objects shallow copy is enough. Then we are pushing a new empty element in that shallow copy. Finally, we are updating that “temp” array with our React state variable.

Now we need to display all the rows with input fields.

{ data.map(function (d, index) {
    return (
        <div key={ `data-${ index }` }
            className="data">
            <input type="text" className="name"
                value={ d.name }
                onChange={ function (event) {
                    const temp = [ ...data ];
                    temp[index].name = event.target.value;
                    setData(temp);
                } }
                placeholder="Name" />

            <input type="text" className="age"
                value={ d.age }
                onChange={ function (event) {
                    const temp = [ ...data ];
                    temp[index].age = event.target.value;
                    setData(temp);
                } }
                placeholder="Age" />

            [ delete button goes here ]
        </div>
    );
} ) }

We are setting the initial value. After that, everytime the value of input field changes, we are again creating a shallow copy of React state variable. Then we are updating the “name” or “age” value at that specific index. event.target.value will return the current value of that input field.

Now we need to find a way to delete the row. Following code goes in the [ delete button goes here ] section.

<button type="button" onClick={ function () {
    const temp = [ ...data ];
    temp.splice(index, 1);
    setData(temp);
} }>Delete</button>

Just like we created a shallow copy for adding a new element in array, we need to create a shallow copy for removing an element as well. We are using Javascript built-in “splice” function to remove 1 element at a specific index. Finally, we are updating the React state variable.

One more thing you can do is to initialize an array. This is useful if you are already receiving a data from your server.

<?php
    $data = [
        [ "name" => "Adnan", "age" => 33 ]
    ];
?>

<input type="hidden" id="data" value="<?php echo htmlentities(json_encode($data)); ?>" />

Here, we are creating a PHP array and setting it’s value in a hidden input field as a JSON string. After that, we need to get that value from hidden input field, parse the JSON string and initialize our array.

let dataArr = document.getElementById("data").value;
dataArr = JSON.parse(dataArr);

const [data, setData] = React.useState(dataArr);

That is how you can add or remove dynamic rows in React. Following is the complete code for this:

<html>
    <head>
        <title>Dynamic rows in React</title>
    </head>

    <body>

        <div id="app"></div>

        <?php
            $data = [
                [ "name" => "Adnan", "age" => 33 ]
            ];
        ?>

        <input type="hidden" id="data" value="<?php echo htmlentities(json_encode($data)); ?>" />

        <script type="text/babel">
            function App () {

                let dataArr = document.getElementById("data").value;
                dataArr = JSON.parse(dataArr);

                const [data, setData] = React.useState(dataArr);

                return (
                    <>

                        { data.map(function (d, index) {
                            return (
                                <div key={ `data-${ index }` }
                                    className="data">
                                    <input type="text" className="name"
                                        value={ d.name }
                                        onChange={ function (event) {
                                            const temp = [ ...data ];
                                            temp[index].name = event.target.value;
                                            setData(temp);
                                        } }
                                        placeholder="Name" />

                                    <input type="text" className="age"
                                        value={ d.age }
                                        onChange={ function (event) {
                                            const temp = [ ...data ];
                                            temp[index].age = event.target.value;
                                            setData(temp);
                                        } }
                                        placeholder="Age" />

                                    <button type="button" onClick={ function () {
                                        const temp = [ ...data ];
                                        temp.splice(index, 1);
                                        setData(temp);
                                    } }>Delete</button>
                                </div>
                            );
                        } ) }

                        <button type="button" onClick={ function () {
                            const temp = [ ...data ];
                            temp.push({
                                name: "",
                                age: ""
                            });
                            setData(temp);
                        } }>Add row</button>

                    </>
                );
            }

            ReactDOM.createRoot(
                document.getElementById("app")
            ).render(<App />);
        </script>

        <script src="js/babel.min.js"></script>
        <script src="js/react.development.js"></script>
        <script src="js/react-dom.development.js"></script>
    </body>
</html>

If you face any problem in following this, kindly do let me know.

Next and previous links in PHP, MySQL

If you see a WordPress site, you will notice that at the bottom of the blog listing page, there will be links to next and previous pages.

They are useful to move the user to next or previous page.

If user is at the last page, then the next button will not be displayed.

Similarly, if user is at the first page, then the previous button will be hidden.

We are achieve this in PHP and MySQL. Following is the code to do that:

<?php

// Create a new PDO connection to the MySQL database
$pdo = new PDO("mysql:host=localhost; dbname=test", "root", "root", [
    PDO::ATTR_PERSISTENT => true // Enables persistent connection for better performance
]);

// Define the number of records to show per page
$per_page = 2;

// Get the current page number from the query string, default to 1 if not set
$page = $_GET["page"] ?? 1;

// Calculate the offset for the SQL query
$skip = ($page - 1) * $per_page;

// Fetch the users for the current page, ordered by ID in descending order
$sql = "SELECT * FROM users ORDER BY id DESC LIMIT $skip, $per_page";
$stmt = $pdo->prepare($sql); // Prepare the SQL statement
$stmt->execute([]); // Execute the query
$users = $stmt->fetchAll(PDO::FETCH_OBJ); // Fetch all results as objects

// Query to get the total number of users in the database
$sql = "SELECT COUNT(*) AS total_count FROM users";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_OBJ);
$total_count = $row->total_count ?? 0; // Get the total count or default to 0

// Calculate the total number of pages required
$total_pages = ceil($total_count / $per_page);

// Determine if there are more pages
$has_more_pages = ($page * $per_page) < $total_count;

// Initialize previous and next page variables
$previous_page = $next_page = null;

// Determine the previous page number
if ($page > 1)
{
    $previous_page = $page - 1;
}

// Determine the next page number
if ($page < $total_pages)
{
    $next_page = $page + 1;
}

?>

<!-- Loop through and display each user -->
<?php foreach ($users as $user): ?>
    <p><?php echo $user->name; ?></p>
<?php endforeach; ?>

<!-- Pagination controls -->
<?php if ($next_page > 0): ?>
    <a href="?page=<?php echo $next_page; ?>">Previous</a>
<?php endif; ?>

<?php if ($previous_page > 0): ?>
    <a href="?page=<?php echo $previous_page; ?>">Next</a>
<?php endif; ?>

Comments has been added with each line for explanation.

Even if you are working in any other language like Node.js and MongoDB, you can still achieve this because now you have the algorithm to do that.

We implemented this technique in one of our project: Multi-purpose platform in Node.js and MongoDB

From there, you will get the idea how you can render next and previous links if you are working in Node.js and MongoDB as backend and React as frontend.

Free tool to write API documentation – PHP, MySQL

I was looking for a tool that allows me to write API documentation so I can provide it to the frontend developers and also for myself. I checked many but didn’t find any that fits to all of my requirements. So I decided to create one of my own. Creating my own tool gives me flexibility to modify it as much as I want.

I also wanted it to share it with other developers who might be having problem in finding the tool to write documentation for their API. So I uploaded it on Github and it is available for anyone for free.

How to write API documentation

A tool is created in PHP and MySQL that allows developers to write API documentation, and this tool is available for free. You can create multiple sections to group the APIs based on modules. For example, user authentication, user posts, comments, replies can be separate sections.

To write each API, you need to tell:

  • The section where it goes.
  • The name of the endpoint. It can be the URL of API.
  • The method, it can be either GET or POST. But since you will have the code, you can add more methods as per your needs.
  • Add a little description about the API, for example what this API does.
  • Headers:
    • You need to tell the key of header, whether it is required or optional. And a little description about the header, for example, it’s possible values.
  • Parameters:
    • Parameters are usually send in the URL. You can define them along with their key, and value and whether they are optional or not.
  • Arguments:
    • For defining the arguments, you need to specify it’s type too. Whether it can be an integer, a string, boolean value or a file object.
  • Example request body. You can write the CURL code inside it to give an example.
  • Status codes and their responses.

I wrote a complete documentation of a project using this tool. You can check that from here.

Download

Assign shirt number to new cricketer – PHP PDO MySQL

Suppose you have a database where data of all players of any sports team is stored. Every player has a name and a shirt number. We will create a program that will generate a new number for new player. We will make sure the new number is not already assigned to any player. We will keep generating new numbers until a unique number is found.

First, create a table “players” in your database by running the following SQL query.

CREATE TABLE IF NOT EXISTS players2 (
    id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    shirt_number INTEGER(11) NOT NULL
);

Then, create a file named “assign-shirt-number-to-new-player.php” and write the following code in it:

// connect with database
$pdo = new PDO("mysql:host=localhost; dbname=test;", "root", "", [
    PDO::ATTR_PERSISTENT => true
]);

This will make a persistent connection with the database. We are using PHP PDO because it has built-in support for SQL injection. After that, you need to fetch all the players already saved in the database.

// fetch all the players from the database
$statement = $pdo->prepare("SELECT * FROM players");
$statement->execute([]);
$rows = $statement->fetchAll(PDO::FETCH_OBJ);

Then we will set the range of numbers in which we want to generate a new number.

// set number of range for shirt numbers
$number_range = 10;

This will generate numbers between 0 and 10. After that, we will create a recursive function that will keep generating a new number unitl a unique shirt number is found.

// recursive function to return the new shirt number
function get_code()
{
    // define global variables to access them inside function
    global $rows, $number_range;

    // if all the numbers are taken, then return -1
    if (count($rows) >= $number_range)
        return -1;

    // generate a random number
    $code = rand(0, $number_range);

    // check if it already exists in the database
    foreach ($rows as $row)
    {
        if ($row->shirt_number == $code) // if number already exists, then start recursion i.e. generate another number
        return get_code();
    }

    // if number not already exists, then return it
    return $code;
}

We need to call this function once to start checking for new unique shirt number.

// initial call to recursive function
$code = get_code();

There is a possibility that all the numbers from 0 to 10 are already taken, in this case, we will display an error message.

// if all numbers are taken, display an error
if ($code == -1)
{
    echo "<p>All numbers are taken.</p>";
    exit;
}

If everything worked fine, we will have a new unique shirt number in our $code variable. We can simply insert it in our database.

// name of new player
$name = "Adnan";

// if shirt number not taken, then insert in database
$statement = $pdo->prepare("INSERT INTO players (name, shirt_number) VALUES (:name, :code)");
$statement->execute([
    ":name" => $name,
    ":code" => $code
]);

// display the new shirt number
echo "<p>New code: " . $code . "</p>";

Complete code

<?php

// connect with database
$pdo = new PDO("mysql:host=localhost; dbname=test;", "root", "root", [
    PDO::ATTR_PERSISTENT => true
]);

// fetch all the players from the database
$statement = $pdo->prepare("SELECT * FROM players");
$statement->execute([]);
$rows = $statement->fetchAll(PDO::FETCH_OBJ);

// set number of range for shirt numbers
$number_range = 10;

// recursive function to return the new shirt number
function get_code()
{
    // define global variables to access them inside function
    global $rows, $number_range;

    // if all the numbers are taken, then return -1
    if (count($rows) >= $number_range)
        return -1;

    // generate a random number
    $code = rand(0, $number_range);

    // check if it already exists in the database
    foreach ($rows as $row)
    {
        if ($row->shirt_number == $code) // if number already exists, then start recursion i.e. generate another number
        return get_code();
    }

    // if number not already exists, then return it
    return $code;
}

// initial call to recursive function
$code = get_code();

// if all numbers are taken, display an error
if ($code == -1)
{
    echo "<p>All numbers are taken.</p>";
    exit;
}

// name of new player
$name = "Adnan";

// if shirt number not taken, then insert in database
$statement = $pdo->prepare("INSERT INTO players (name, shirt_number) VALUES (:name, :code)");
$statement->execute([
    ":name" => $name,
    ":code" => $code
]);

// display the new shirt number
echo "<p>New code: " . $code . "</p>";

Check if URL is valid – PHP

In order to check if a URL is valid in PHP, we are going to use the cURL. You can get the complete reference on cURL from php.net. First, we are going to create a variable that will hold the value of URL that needs to be checked.

<?php

// URL to check
$url = "https://adnan-tech.com/";

Then, we are going to initialize the cURL.

// Initialize cURL
$curl = curl_init();

After that, we need to set the URL of cURL and make sure to return the response from server. For this, we will use cURL options.

// Set cURL options
curl_setopt_array($curl, [
    // Set URL
    CURLOPT_URL => $url,

    // Make sure to return the response
    CURLOPT_RETURNTRANSFER => 1
]);

Finally, we can execute this cURL request.

// Execute the CURL request
$response = curl_exec($curl);

Then, we will get the error from response (if there is any). If there is no error in response, it means that the URL is valid and the curl_error will return an empty string.

// Get error from CURL, it will be empty if there is no error.
$error = curl_error($curl);

We can put a condition on this variable to check if this variable has some value, it means there is an error in the request. In that case, we will display the error and stop the script. Otherwise, we will display a message that the URL is valid.

// If not empty, display the error and stop the script.
if ($error)
    die($error);

// Else, the URL is valid
echo "Valid";

Here is the complete code.

<?php

// URL to check
$url = "https://adnan-tech.com/";

// Initialize CURL
$curl = curl_init();

// Set CURL options
curl_setopt_array($curl, [
    // Set URL
    CURLOPT_URL => $url,

    // Make sure to return the response
    CURLOPT_RETURNTRANSFER => 1
]);

// Execute the CURL request
$response = curl_exec($curl);

// Get error from CURL, it will be empty if there is no error.
$error = curl_error($curl);

// If not empty, display the error and stop the script.
if ($error)
    die($error);

// Else, the URL is valid
echo "Valid";

That’s how you can check if a URL is valid or not in PHP.

Sort custom post type by ID ascending – WordPress

Suppose you have custom post type in WordPress that you want to sort such that it displays the first created post on top. By default, WordPress sort the posts by ID in descending. That means that the latest uploaded post will be displayed on top, which is good in many cases. But there might be a scenario where you want the first post to be displayed first. In this post, we will teach you how to do it using our Social Network API custom post type.

First, you need to go to your WordPress admin panel and navigate to Appearance -> Theme File Editor. In that page, select your current theme and find it’s “index.php” file and open it. In this file, search for a code:

<?php if ( have_posts() ) : ?>

Inside this “if” condition, and before the while loop:

<?php while ( have_posts() ) : the_post(); ?>

Write the following code, make sure to replace “social-network-api” with your own custom post type where you want to apply this sort.

<?php if ( have_posts() ) : ?>
                        
    <?php
        $post_type = $_GET["post_type"] ?? "";
        if ($post_type == "social-network-api"):
            query_posts([
                "post_type" => $post_type,
                "posts_per_page" => 10,
                "orderby" => "ID",
                "order" => "ASC"
            ]);
        endif;
    ?>

    <?php while ( have_posts() ) : the_post(); ?>

    <?php endwhile; ?>

<?php endif; ?>

If you refresh the page now, you will see your first post be displayed first.

How to generate random string in PHP

In this article, I will show you, how you can generate a random string in PHP. You can set the length of random string. Also, you can define all the possible characters you want in your random string.

In order to generate random string in PHP, we will first create a string of all the possible characters we want in our random string.

$str = "qwertyuiopasdfghjklzxcvbnm";

Then we are going to get the length of that string.

$str_length = strlen($str);

After that, we will create a variable that will hold the output value i.e. random string.

$output = "";

Loop through the number of characters you want in your random string.

$length = 6;

for ($a = 1; $a <= $length; $a++)
{
    // [section-1]
}

On the place of [section-1], we will get the random index from string of possible characters.

$random = rand(0, $str_length - 1);

And we will pick the random character from that string.

$ch = $str[$random];

Finally, we will append that character in our output string.

$output .= $ch;

If you echo $output; you will see a random string every time that code is executed. Here is the full code:

$str = "qwertyuiopasdfghjklzxcvbnm";
$str_length = strlen($str);
$output = "";
$length = 6;
for ($a = 1; $a <= $length; $a++)
{
    $random = rand(0, $str_length - 1);
    $ch = $str[$random];
    $output .= $ch;
}
echo $output;

Freelance Status – A tool for freelancers

Freelance Status is a tool for freelancers to update clients about their work progress. You can download it for free.

Technologies used

  • Laravel
    • I have used Laravel framework for building this project basic structure and APIs. It is also a very good framework with many built-in security features. It can also be deployed on shared hosting as well.
  • React JS
    • All the pages on client and admin side are rendered in React JS. This is not a Single Page Application (SPA) but the HTML is rendered by React JS.
  • Bootstrap
    • Bootstrap is used for building structure and layout of website. It is also very helpful for responsive design.

Features

In “Freelance Status”, there are 2 panels. One for freelancer and one for client. Freelancer portal is actually the admin panel because he can add his clients, projects and tasks. He can update the status of his tasks etc. But client can only see the progress of their tasks from user side.

Admin panel (freelancer)

You (as a freelancer) holds the admin panel. You can:

  • Add, edit or delete clients. While adding clients, you can enter their name, email, phone (if have) and password. You can let them know their password via message or inbox so they can access the client side.
  • You can add projects for each client. While adding projects, you can enter the name of the project. Then you can select the client of that project via dropdown. In dropdown, you will see a list of all clients added from previous step.
  • Similarly, you can add tasks of each project. For adding tasks, you have to provide many values.
    • Task title and its description.
    • The price of that task.
    • The status (todo, progress or done).
    • The payment status. It can be either (paid, not paid, not finalized). Payment “not finalized” means that the amount is not yet decided between client and freelancer. But you are saving the task so it can be discussed later.
    • Select the client.
    • Select the project this task belongs to.

Client side

  • Clients will first have to login using the email and password provided by freelancer.
  • After login, they will see all their projects on home page.
  • With each project, they will see a link “View tasks”. On clicking that, they will be redirected to a new page.
  • On this page, they can see a list of all tasks in that project. They can also see the price, status and payment status of each task.
  • With each task, a button saying “Detail” is displayed. When clicked, will display a modal containing the details of the task.

Installation

Following steps helps you install this project on your localhost. If you want to learn how to deploy this on your live server, check our this guide.

Step 1

First you need to create a database named “freelance_status”, or any other name of your choice, in your phpMyAdmin.

Step 2

Then you need to set your database credentials in “config/database.php” file. Here you can set your database name, username and its password.

Note: If you are working on live server, make sure you have given that user all permissions to your database.

Step 3

Open command prompt or terminal at the root of this project and run the following commands:

COMPOSER_MEMORY_LIMIT=-1 composer update

This will install all the required libraries for this project. Make sure you have composer installed in your system. COMPOSER_MEMORY_LIMIT=-1 will prevent you from timeout exception.

Note: For live server, you can talk with your hosting provider customer support to install composer.

Step 4

Set storage link in your public folder by running the following command:

php artisan storage:link

This will create a shortcut link of storage/app/public folder into your public folder. It allows you to access your files stored in storage from public directory.

Step 5

Next step is to generate an application key for your project.

php artisan key:generate

This will generate a random string of 32 characters. The key will automatically be saved in APP_KEY variable of your .env file.

Step 6

If you have set your database credentials, you can run the following command.

php artisan migrate

It will create all the tables required for your project.

Step 7

After running the migration, we need to run the seeder.

name="Admin" email="admin@gmail.com" password="admin" php artisan db:seed –class=DatabaseSeeder

A super admin will be added in “users” table. You can set your own name, email and password here.

Step 8

Finally you can run your project by running the following command.

php artisan serve

If you run the URL “http://127.0.0.1:8000” in your browser, you will see your project. If anything goes wrong, feel free to contact me.

“Freelance Status” allows you to add clients, their projects and tasks from admin panel. And clients can see them trough a user side. Clients do not have to keep asking you about update on the project. And you can focus more on work than on updating the client about progress.

Capitalize string in PHP

In this blog post, you will learn how you can capitalize a string in PHP. We will not use any external library for this purpose. This code can be used in any PHP framework (Laravel, Yii) because I have not used any dependency for it. We will also teach you, how you can update the array element inside foreach loop in PHP.

First, we will explode the string by space.

<?php

// input string
$str = "adnan afzal";

// split words by space
$parts = explode(" ", $str); // ["adnan", "afzal"]
  • explode(delimiter, string): This is a PHP built-in function used to split the string into an array using a delimiter. Here, we are splitting the string using space. So it will return an array of all words in a string.

Then we will loop through all words one-by-one:

// loop through each word
foreach ($parts as $key => $value)
{
    // [section-1]
}

Inside the loop, we will update the word by uppercasing the first letter of each word. Write the following code in [section-1]:

// make first letter uppercase
// and update the word
$parts[$key] = ucfirst($value); // converts ["adnan"] to ["Adnan"]
  • ucfirst(string): This is another PHP built-in function and it is used to uppercase the first letter of the string. So “adnan” will became “Adnan”.

We are converting all the words first letter to uppercase and update the word itself. You can update the array value inside foreach loop using the $key variable.

After the loop, we will join all array parts by space.

// join all words by space
$str = implode(" ", $parts); // converts ["Adnan", "Afzal"] to "Adnan Afzal"

// output string
echo $str;
  • implode(glue, pieces): This function will join the array into a string using a glue. In this case, we are joining the array using space.

Complete code

Following is the complete code to capitalize the string in PHP:

<?php

// input string
$str = "adnan afzal";

// split words by space
$parts = explode(" ", $str); // ["adnan", "afzal"]

// loop through each word
foreach ($parts as $key => $value)
{
    // make first letter uppercase
    // and update the word
    $parts[$key] = ucfirst($value);
}

// join all words by space
$str = implode(" ", $parts);

// output string
echo $str;

Bonus

There might be some cases where you have a value in database like “processing_order” and you want it to display like “Processing Order”. In this case, you just have to add 1 line before using explode() function.

$str = "processing_order";
$str = str_replace("_", " ", $str); // processing order

Then you can apply the above code to capitalize the string. If you want to learn how to capitalize string in Javascript, follow this.

Encode decode JWT in PHP

JWT (Json Web Tokens) can be used for user authentication. They are token-based. First, you need to encode the token and send it to the client. Client will save it in his local storage or cookie. In order to decode the token, user must provide the token. Both encode and decode function on JWT wll be performed on server side in PHP.

Although I did JWT authentication with Python and Mongo DB and with Node JS and Mongo DB. But today we do it for PHP developers.

Install php-jwt

First, you need to install a library called “php-jwt”.

You can install it from composer:

COMPOSER_MEMORY_LIMIT=-1 composer require firebase/php-jwt

Or you can download and include it manually in your PHP project.

Encode JWT in PHP

When admin is logged-in, we need to generate his authentication token. First, you need to include the JWT and Key class on top of your file.

require_once "vendor/autoload.php";

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

Following code will generate a JWT using ID.

$jwt_key = "your_secret_key"; // This should be consistent

$issued_at = time();

// $expiry = strtotime("+30 days");

// jwt valid for 30 days (60 seconds * 60 minutes * 24 hours * 30 days)
$expiry = $issued_at + (60 * 60 * 24 * 30);

$payload = [
    'iss' => 'https://your-website.com',
    'aud' => 'https://your-website.com',
    'iat' => $issued_at, // issued at
    'nbf' => $issued_at, //  not before
    'exp' => $expiry, // expiry time
    "id" => 1
];

$jwt = JWT::encode($payload, $jwt_key, 'HS256');
  • Here, we have set the expiry date of this token to 30 days.
  • iss: Issuer. It tells who issued this token. Usually it is a URL of the server from where the JWT is being generated.
  • aud: Audience. This tells who can use this token. By providing the URL of your website, you are telling that this token will be valid if it comes from your website only. You can also pass it as an array if you want to allow multiple audience for same token.
  • iat: It will be a timestamp in seconds since January 01, 1970 00:00:00 UTC.
  • nbf: The timestamp seconds after which the token can be used. Token provided before this time will not be accepted. We are setting it same as issued time, so you will be able to use it as soon as you generate it.
  • exp: This will be the timestamp in seconds when the token will be expired. It will also be timestamps seconds since January 01, 1970 00:00:00 UTC. We are setting it’s validity for 30 days.
  • id: Optional. This is the custom claim that we are attaching with JWT. So when we decode the token, we will get this ID. This ID can be used to check if the user still exists in the database.

Here we are using HS256 algorithm that is used for authentication in JWT. It is a combination of 2 cryptographic methods:

  1. HMAC (Hash-based Message Authentication Code)
  2. SHA-256 (Secure Hash Algorithm 256 bit)

HMAC

HMAC combines cryptographic hash function with a secret key, in this case it will be $jwt_key. It ensures that the token is not been changed and is sent from the owner of secret key (your server).

SHA-256

SHA-256 generates a 256-bit hash from any given value. It is a one-way encryption method. It means that once the hash is generated, it cannot be decrypted back to its original state. So you will not be able to see the original message once it is encrypted.

So in JWT::encode function call, we are sending our payload and secret key. We are also telling the php-jwt library to use the HS256 algorithm. It takes our payload and encrypt it with our secret key and return the hash.

You do not have to save this token in your database. Just return it as a response to AJAX request and user can save it in his local storage.

localStorage.setItem("accessToken", accessToken)

To save the token on user side, we are using localStorage web API. This will keep the access token in local storage until removed using Javascript localStorage.removeItem(“accessToken”) or if the browsing history is deleted. However, it can store only upto 10 MB. But that will be enough in this case. The token generated will be a string of just a few bytes.

It stores the data in key-value pair. In this case, our key is “accessToken” and our value is the accessToken received from server.

Note: The first parameter is a string and second is a variable.

Decode JWT in PHP

Now whenever admin sends an AJAX request, he needs to pass that access token in headers.

const ajax = new XMLHttpRequest();
ajax.open("POST", "index.php", true)

ajax.setRequestHeader("Authorization", "Bearer " + localStorage.getItem("accessToken"))

ajax.send()

Here, we are first creating an AJAX (Asynchronous JavaScript and XML) object. Then we are opening the request with method POST and the server URL is “index.php”, you can write your own route. Third parameter is async, it’s default value is also true. It means that the request will be processed asyncronously. If you use false, it will not return any value until the response is received, thus blocking the UI which is not good for user experience.

After that, we are attaching Authorization header with the AJAX request. It is a good practice to send authorization tokens in header for security and it is also a standardized way of sending tokens. So if you are developing a website or a mobile application, every developer will know that the token needs to be sent in the header.

We are using Bearer authorization token because they hide the sensitive data that we are sending in payload. Thus, even if someone reads the headers, he won’t be able to read the ID of user. And we are fetching the token value from local storage we saved earlier.

Finally, we are sending the request. If you are to send some data with the request too, you can send it in FormData object. Check our tutorial on how to send AJAX request with FormData.

Then on server side, we need to get the access token from Authorization header and decode it to see if it is valid.

// index.php

// Get the JWT from the Authorization header
try
{
    $headers = getallheaders(); // returns an array of all headers attached in this request

    if (!isset($headers['Authorization']))
    {
        echo json_encode([
            "status" => "error",
            "message" => "'authorization' header not present."
        ]);
        
        exit();
    }

    $auth_header = $headers['Authorization'];
    list($jwt) = sscanf($auth_header, "Bearer %s");

    $decoded = JWT::decode($jwt, new Key($jwt_key, 'HS256'));
    $id = $decoded->id;

    return $id;
}
catch (\Exception $exp)
{
    echo json_encode([
        "status" => "error",
        "message" => $exp->getMessage()
    ]);

    exit();
}

First, we are fetching all the headers from the request. Then we are checking if the Authorization header is present in the request. If not, then we are throwing an error. So if user fails to attach the Authorization header in the request, it will not process further.

  • sscanf: This function is used to read and parse the value from a string. While “sprintf” is used to only format the data, but this function reads the data and parses as well.
  • Our format “Bearer %s” tells the function to expecct Bearer at the start of the string. And %s tells it to put the remaining string in a variable.
  • list() is a built-in function in PHP. It is used to assign multiple values to multiple variables respectively. In this case, we are assigning value of “%s” to $jwt variable.

After that, we are decoding the token. Decode function in JWT PHP is a little different than the encode function. First parameter is the token, second is an instance of Key class from php-jwt library. It also accepts 2 parameters, first is the secret key used to generate the token and second is the algorithm used while generating the token. If there is any mismatch in token, secret key or algorithm, it will throw an exception and we will receive that in catch block.

It will return the payload that we are saving in $decoded variable. From this decoded variable, you can get the ID of the authenticated user.

That’s how you can encode and decode the JWT in PHP. If you face any problem in following this, kindly do let me know.