session_start();
if (kosong($_SESSION['token'])) {
$_SESSION['token'] = bin2hex(random_bytes(32));
$ token = $_SESSION['token'];
session_start();
jika (kosong($_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'];
Gunakan hash_equals() untuk mengesahkan token dengan selamat:
jika (!kosong($_POST['token'])) {
if (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 }
echo hash_hmac('sha256', '/my_form.php', $_SESSION['second_token']);
$twigEnv->addFunction(
new \Twig_SimpleFunction( 'form_token', function($lock_to = null) { if (empty($_SESSION['token'])) { $_SESSION['token'] = bin2hex(random_bytes(32)); } if (empty($_SESSION['token2'])) { $_SESSION['token2'] = random_bytes(32); } if (empty($lock_to)) { return $_SESSION['token']; } return hash_hmac('sha256', $lock_to, $_SESSION['token2']); } )
Atas ialah kandungan terperinci Mengapakah token CSRF saya kadangkala kosong apabila digunakan dalam AJAX dan borang standard, dan bagaimana saya boleh membetulkannya dalam PHP?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!