Skip to content

rudSarkar/simple-csrf-protection-php

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 

Repository files navigation

simple-csrf-protection-php

Simple CSRF Protection PHP

How it work

  1. Start session
  2. Generate uniqid
  3. validate uniqid
  4. Add CSRF token in hidden input of HTML Form

Start session

session_start();

Generate a uniqid

$_SESSION['key'] = md5(uniqid(rand(), TRUE));

Validate uniqid

if (isset($_POST['csrf']) && $_SESSION['key'] === $_SESSION['key'])
  {
      echo "Your name is: " . $_POST['username'];
  } else
      echo "CSRF Token Failed !";

Add CSRF token in hidden input of HTML Form

<input type="hidden" name="csrf" value="<?php echo $_SESSION['key']; ?>">

Full Code

<?php
    // Start a session
    //session_start();

    if (empty($_SESSION['key'])) {
        $_SESSION['key'] = md5(uniqid(rand(), TRUE));
    }

    if (isset($_POST['submit'])) {
        if (isset($_POST['csrf']) && $_SESSION['key'] === $_SESSION['key'])
        {
            echo "Your name is: " . $_POST['username'];
        } else
            echo "CSRF Token Failed !";
    }
?>

<!DOCTYPE html>
<html>
<head>
    <title>Simple CSRF Protection PHP</title>
</head>
<body>
    <form method="POST" action="index.php">
        <input type="text" name="username" placeholder="your name">
        <input type="hidden" name="csrf" value="<?php echo $_SESSION['key']; ?>">
        <input type="submit" name="submit" value="submit">
    </form>
</body>
</html>

[N.B: I am disable SESSION_START because when i am disable it, It will starting to generate random uniqid]

If you are still confused knock me on Facebook