What is CSRF Token and How To Use in Core PHP Tutorial

Reading Time: 9 minutes
623 Views

Inside this article we will see the concept i.e What is CSRF Token and How To Use in Core PHP Tutorial. Article contains the classified information i.e Cross-site Request Forgery (Anti-CSRF) Protection in PHP.

A security tool called a CSRF token is used in online applications to prevent Cross-Site Request Forgery (CSRF) attacks. Every form that is submitted to the server contains a random number that the server has created. Before processing the form submission, the server then verifies the token value to make sure the form was submitted by the authorised user and not by a malicious website.

Read More: How Many Different ways of Writing Functions in JavaScript

Let’s get started.

What is a CSRF Token?

Cross-Site Request Forgery (CSRF) is an attack where a malicious website sends unauthorized commands from a user’s browser to a vulnerable web application that the user is currently logged in to. This type of attack can result in data breaches, identity theft, and unauthorized access to sensitive information.

To prevent CSRF attacks, web developers can use a security mechanism called CSRF tokens. A CSRF token is a random value that is generated by the server and included in every form that is submitted to the server. The token is then checked by the server before it processes the form submission, ensuring that the form was submitted by the authorized user and not by a malicious website.

Why we use CSRF token in application development?

We use CSRF (Cross-Site Request Forgery) tokens to prevent malicious attacks on web applications. CSRF attacks occur when a user unknowingly submits a form on a website that has been tampered with by an attacker.

This can result in the attacker performing actions on the user’s behalf without their knowledge or consent, such as changing their password, transferring funds, or making unauthorized purchases.

Read More: How To Prevent Website From Being Loaded in Iframe

By using CSRF tokens, web applications can ensure that all form submissions come from an authorized source, preventing attackers from exploiting vulnerabilities and performing unauthorized actions on behalf of users.

PHP Functions To Generate CSRF Token

In PHP, there are several functions that can be used to create a CSRF token value. Here are some examples:

bin2hex()

This function converts binary data into a hexadecimal representation. You can use it to generate a random string of bytes and then convert it to hexadecimal to create a CSRF token.

// generates a random 32-byte string and converts it to hexadecimal
$token = bin2hex(random_bytes(32)); 

openssl_random_pseudo_bytes()

This function generates a string of pseudo-random bytes using the OpenSSL library. You can use it to create a random string of bytes and then convert it to hexadecimal to create a CSRF token.

// generates a random 32-byte string and converts it to hexadecimal
$token = bin2hex(openssl_random_pseudo_bytes(32));

uniqid()

This function generates a unique identifier based on the current time in microseconds. You can use it to create a random string of characters to use as a CSRF token.

// generates a unique identifier based on the current time in microseconds
$token = uniqid();

md5()

This function calculates the MD5 hash of a string. You can use it to generate a hash value from a random string of bytes, which can be used as a CSRF token.

// generates a random 32-byte string
$bytes = random_bytes(32);

// calculates the MD5 hash of the random string of bytes
$token = md5($bytes); 

It’s important to note that generating a CSRF token value is just one part of implementing CSRF protection in your PHP application. You also need to include the token in every form that requires CSRF protection, store it securely, and validate it when the form is submitted.

Read More: How to Create a Password Strength Validator in PHP Tutorial

Cross-site Request Forgery (Anti-CSRF) Protection in PHP

In PHP development, implementing CSRF tokens is relatively simple. Here is a step-by-step guide on how to use CSRF tokens in PHP:

  1. Generate a unique token for each user session.
  2. Store the token in a hidden field in every form that requires CSRF protection. This field can be added to the form using PHP’s built-in htmlspecialchars() function to prevent cross-site scripting (XSS) attacks.
  3. When the form is submitted, check the token value against the stored token value for that user session. If the tokens do not match, reject the form submission.

Step 1: Generate a CSRF Token and Store

Generate a CSRF token and store it in the user’s session when the user logs in or starts a new session. You can use the bin2hex() function to generate a unique token.

session_start();
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

Step 2: Add CSRF token

Include the CSRF token in every form that requires CSRF protection. You can add the token as a hidden field in the form, using the htmlspecialchars() function to prevent cross-site scripting (XSS) attacks.

<form action="submit.php" method="post">
    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
    <input type="text" name="username">
    <input type="password" name="password">
    <input type="submit" value="Submit">
</form>

Step 3: Validate CSRF token

Check the CSRF token when the form is submitted. You can do this by comparing the token value in the form submission with the token stored in the user’s session.

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        // CSRF token validation failed, handle the error
    } else {
        // CSRF token validation succeeded, process the form submission
    }
}

By following these steps, you can use CSRF tokens to protect your Core PHP web application from CSRF attacks.

Read More: Step by Step To Build Your Own Chrome Extension Tutorial

A Basic Program (Complete Code)

Here is an example code snippet that generates and checks CSRF tokens in PHP:

<?php
session_start();

// Generate a unique CSRF token for the user session
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Add the CSRF token to the form
<form action="submit.php" method="post">
    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
    <input type="text" name="username">
    <input type="password" name="password">
    <input type="submit" value="Submit">
</form>


// Check the CSRF token when the form is submitted
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
    // Process the form submission
} else {
    // Reject the form submission
}
?>

We hope this article helped you to learn What is CSRF Token and How To Use in Core PHP Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more