Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Created May 31, 2023 03:45
Show Gist options
  • Save code-boxx/656fef9a09eae605308bacbfd6f3e849 to your computer and use it in GitHub Desktop.
Save code-boxx/656fef9a09eae605308bacbfd6f3e849 to your computer and use it in GitHub Desktop.
Very Simple PHP CSRF Token

VERY SIMPLE PHP CSRF TOKEN

https://code-boxx.com/simple-csrf-token-php/

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

<?php
// (A) GENERATE CSRF TOKEN (RANDOM STRING INTO SESSION)
// CREDITS : https://stackoverflow.com/questions/6287903/how-to-properly-add-csrf-token-using-php
session_start();
$_SESSION["token"] = bin2hex(random_bytes(32));
$_SESSION["token-expire"] = time() + 3600; // 1 hour = 3600 secs
// (B) EMBED TOKEN INTO FORM ?>
<form method="post" action="2-submit.php">
<input type="hidden" name="token" value="<?=$_SESSION["token"]?>">
<input type="email" name="email" value="jon@doe.com">
<input type="submit" value="Go!">
</form>
<?php
// (A) START SESSION
session_start();
// (B) COUNTER CHECK SUBMITTED TOKEN AGAINST SESSION
if (
isset($_POST["token"]) &&
isset($_SESSION["token"]) &&
isset($_SESSION["token-expire"]) &&
$_SESSION["token"]==$_POST["token"]
) {
// (B1) EXPIRED
if (time() >= $_SESSION["token-expire"]) {
exit("Token expired. Please reload form.");
}
// (B2) OK - DO YOUR PROCESSING
unset($_SESSION["token"]);
unset($_SESSION["token-expire"]);
echo "OK";
}
// (C) INVALID TOKEN
else { exit("INVALID TOKEN"); }
<?php
// (A) GENERATE CSRF TOKEN (RANDOM STRING INTO SESSION)
session_start();
$_SESSION["token"] = bin2hex(random_bytes(32));
$_SESSION["token-expire"] = time() + 3600; // 1 hour = 3600 secs
// (B) EMBED TOKEN INTO FORM AS USUAL ?>
<form id="myForm" onsubmit="return doAJAX()">
<input type="hidden" name="token" value="<?=$_SESSION["token"]?>">
<input type="email" name="email" value="jon@doe.com">
<input type="submit" value="Go!">
</form>
<script>
function doAJAX () {
// (C) GET FORM DATA
var data = new FormData(document.getElementById("myForm"));
// (D) AJAX FETCH
fetch("2-submit.php", { method: "POST", body: data })
.then(res => res.text())
.then(res => {
// DO WHATEVER YOU NEED
console.log(res);
// if (res=="OK") { ... }
})
.catch(err => console.error(err));
return false;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment