For security code, please don’t generate your tokens this way: $token = md5(uniqid(rand(), TRUE));
rand() is predictable
uniqid() only adds up to 29 bits of entropy
md5() doesn’t add entropy, it just mixes it deterministically
Try this out:
Generating a CSRF Token
PHP 7
session_start();
if (empty($_SESSION[‘token’])) {
$_SESSION[‘token’] = bin2hex(random_bytes(32));
}
$token = $_SESSION[‘token’];
Sidenote: One of my employer’s open source projects is an initiative to backport random_bytes() and random_int() into PHP 5 projects. It’s MIT licensed and available on Github and Composer as paragonie/random_compat.
PHP 5.3+ (or with ext-mcrypt)
session_start();
if (empty($_SESSION[‘token’])) {
if (function_exists(‘mcrypt_create_iv’)) {
$_SESSION[‘token’] = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
} else {
$_SESSION[‘token’] = bin2hex(openssl_random_pseudo_bytes(32));
}
}
$token = $_SESSION[‘token’];
Verifying the CSRF Token
Don’t just use == or even ===, use hash_equals() (PHP 5.6+ only, but available to earlier versions with the hash-compat library).
if (!empty(KaTeX parse error: Expected '}', got 'EOF' at end of input: …f (hash_equals(_SESSION[‘token’], $_POST[‘token’])) {
// Proceed to process the form data
} else {
// Log this as a warning and keep an eye on these attempts
}
}
地址:http://stackoverflow.com/questions/6287903/how-to-properly-add-csrf-token-using-php