Skip to content

Instantly share code, notes, and snippets.

@volbil
Created January 8, 2019 11:17
Show Gist options
  • Save volbil/0a145c566dd291fd0ac6fed06bafcaa0 to your computer and use it in GitHub Desktop.
Save volbil/0a145c566dd291fd0ac6fed06bafcaa0 to your computer and use it in GitHub Desktop.
<?php
class CSRF {
public function __construct() {
if (!isset($_SESSION['csrfToken'])) {
$_SESSION['csrfToken'] = [];
}
}
public static function generate() {
$token = base64_encode(openssl_random_pseudo_bytes(32));
return $_SESSION["csrfToken"][$token] = $token;
}
public static function check($token) {
if (!empty($_SESSION["csrfToken"][$token]) && $token === $_SESSION["csrfToken"][$token]) {
if ($_SESSION["csrfToken"][$token]) {
unset($_SESSION["csrfToken"][$token]);
return true;
}
}
return false;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment