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.
The class must be configured in order to run.
$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.
It allows you to call the generated token so you can add it to your forms.
$csrf->Get();
C8/mA9vfc4ST1D8+hSVrjKOaA2Y+UcVYvIBaEbYXKTN45DQVe1+qO29ntVDqSx2p4Xp3MrjiTh8lihWSK0Uo6b2jUbWzO+8DbCIieY0wYwE=
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.
$csrf->Check($token);
true/false
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.
$csrf->Reset();
true/false
<?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>