Addressing Cross-Site Request Forgery

Cross-site Request Forgery (CSRF, XSRF, or Sea Surf) is attempt to trick a victim into making an HTTP request that the victim did not intend to make and a forged request is sent to the web server. Upon sending the request, the browser includes the Cookie header with a session identifier.

When a user submits an authenticated request that requires a Cookie, the anti-CSRF token should be included in the request. The application verifies if token is valid or existed and if not, the request is rejected.

Implementation in PHP:

// index.php

//start session

//create a key
if (empty($_SESSION['key']))
  $_SESSION['key'] =  bin2hex(random_bytes(32));

//create cdrf token
$csrf = hash_hmac('sha256', 'string of data', $_SESSION['key']);

//validate token on submit
if (isset($_POST['submit'])) {
  //check if token is the same
  if (hash_equals($csrf, $_POST['csrf']))
    echo "Username is " . $_POST['username'];
    echo "CSRF token failed!";
<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Validate CSRF</title>
  <form method="post" action="index.php">
    <input type="text" name="username" placeholder="your name" />
    <input type="hidden" name="csrf" value="<?php echo $csrf ?>" />
    <input type="submit" name="submit" value="Submit">