Skip to content

BMathers35/php_basic_csrf

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

php_basic_csrf

Simple CSRF control class with PHP. With this php class you can generate and validate tokens that are disposable or refreshed on every page refresh. The generated tokens are encrypted with openssl for extra security, so you need the openssl extension on your php server.

Configuration

The class must be configured in order to run.

Configuration Example
$csrf = new Csrf([
  'key' => 'SuperKey', // Key
  'secret' => 'SuperSecret' // Secret Key
]);

The Key and Secret values are used to encrypt the tokens when generating, so enter these values once and do not change them.

Get()

It allows you to call the generated token so you can add it to your forms.

Get() Example
$csrf->Get();
Get() Example Result

C8/mA9vfc4ST1D8+hSVrjKOaA2Y+UcVYvIBaEbYXKTN45DQVe1+qO29ntVDqSx2p4Xp3MrjiTh8lihWSK0Uo6b2jUbWzO+8DbCIieY0wYwE=

Check()

It compares the token you have printed on your forms with the token registered in the session and checks its accuracy. Create a _csrf entry in your forms and print the value generated by the class using the Get() method.

Check() Example
$csrf->Check($token);
Check() Result

true/false

Reset()

Use this method to reset and regenerate the token after verifying the token. If you want, you can increase the security a little more by creating a new token every time the page is refreshed.

Reset() Example
$csrf->Reset();
Reset() Result

true/false

Example Form Usage and Controls

<?php

    session_start(); // Start sessions.
    // Include the CSRF Class in your file.

    // Configure the class.
    $csrf = new Csrf([
        'key' => 'SuperKey',
        'secret' => 'SuperSecret'
    ]);

    if($_POST){

        $firstname = $_POST['firstname'];
        $_csrf = $_POST['_csrf']; // We get the _csrf value from the form.

        // We verify the token from the form with the Check() method.
        if($csrf->Check($_csrf)){ 

            $result = "Token is correct";
            $csrf->Reset(); // We reset the token.

        }else{

            $result = "Token is not correct";
            $csrf->Reset(); // We reset the token.

        }

    }

?>

<form method="POST" action="post.php">
    <input type="text" name="firstname"><br>
    <input type="text" name="_csrf" value="<?= $csrf->Get(); ?>"><br>
    <button type="submit">Submit</button>
</form>