PHP 8 interview question · Most asked
How do you protect a PHP app against CSRF and session attacks?
Summary
Use per-session CSRF tokens on state-changing requests, SameSite cookies, session_regenerate_id(true) on login, and secure cookie flags (Secure, HttpOnly).
Longer Answer
CSRF: generate bin2hex(random_bytes(32)), store it in the session, embed it in forms, and compare with hash_equals(). SameSite=Lax blocks most cross-site POSTs. Session fixation: regenerate the ID after authentication or privilege change. Also set session.use_strict_mode=1 and session.cookie_secure=1, and expire idle sessions server-side.
Code Example
<?php
session_set_cookie_params(['secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
session_start();
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
if ($_SERVER['REQUEST_METHOD'] === 'POST'
&& !hash_equals($_SESSION['csrf'], $_POST['csrf'] ?? '')) {
http_response_code(419);
exit('Invalid CSRF token');
}
Key Points
- Token +
hash_equals()for CSRF SameSite=Lax/Strictcookiessession_regenerate_id(true)on loginsession.use_strict_mode=1
More most-asked PHP 8 questions
- What are the most important features introduced in PHP 8.0?
- What happens to an HTTP request in a PHP-FPM application, and what does 'shared nothing' mean?
- How should passwords be stored in PHP?
- What are named arguments and what are their benefits and risks?
- What is constructor property promotion?
- How does `match` differ from `switch`?
- What are union types in PHP 8 and how do you use them?
- What are enums in PHP 8.1? Explain pure vs backed enums.