What is CSRF protection and why is it important in PHP?
CSRF protection is important in PHP to prevent Cross-Site Request Forgery attacks, where an attacker tricks a user into unknowingly executing actions on a website they are authenticated on. To protect against CSRF attacks, developers can generate a unique token for each user session and include it in forms. When a form is submitted, the server can verify that the token matches the one associated with the user's session.
// Generate CSRF token and store it in the user's session
session_start();
if (!isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
// Include the CSRF token in forms
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
// Verify CSRF token on form submission
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
// Invalid CSRF token, handle error
die('CSRF token validation failed');
}
Related questions
-
PHP hierarchical menu submenus
-
PHP jump file redirection
-
PHP form submission userfile array