Skip to content

Instantly share code, notes, and snippets.

@arnissolle
Last active October 5, 2019 13:58
Show Gist options
  • Select an option

  • Save arnissolle/5c2cecec33ce757cb07bb0b119f6bb20 to your computer and use it in GitHub Desktop.

Select an option

Save arnissolle/5c2cecec33ce757cb07bb0b119f6bb20 to your computer and use it in GitHub Desktop.
CSRF Protection
<?php
class CSRF
{
public static $salt = null;
public static function getToken($force_renew_token = false)
{
if ($force_renew_token || !self::hasValidToken())
{
self::renewToken();
}
return $_SESSION['csrf']['token'];
}
public static function checkTokenValidity($untrusted_token = null, $allowed_methods = array('GET'))
{
if (in_array($_SERVER['REQUEST_METHOD'], $allowed_methods))
{
return true;
}
if ( ! self::hasValidToken())
{
return false;
}
$untrusted_token = ($untrusted_token ?: $_POST['csrf-token']) ?: $_SERVER['HTTP_CSRF_TOKEN'];
$isValidToken = $untrusted_token === self::getToken();
return $isValidToken;
}
private static function hasValidToken()
{
if ( ! array_key_exists('csrf', $_SESSION))
{
return false;
}
$hasToken = $_SESSION['csrf']['token'];
$isNotExpired = time() < $_SESSION['csrf']['expires_at'];
return $hasToken && $isNotExpired;
}
/**
* @param int $lifetime: token lifetime in seconds
*/
private static function renewToken($lifetime = 3600)
{
$hash = sha1(uniqid(mt_rand()) . self::$salt);
$token = base_convert($hash, 16, 36);
$expires_at = time() + $lifetime;
$_SESSION['csrf'] = array(
'token' => $token,
'expires_at' => $expires_at
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment