Interview question
What is CSRF and how do you protect forms against it in PHP? CSRF क्या है और PHP forms को इससे कैसे बचाएं?
Answer
CSRF (Cross-Site Request Forgery) tricks an authenticated user's browser into submitting a request they didn't intend, using their existing session cookies.
// Generate token and store in session
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
// In the form
<input type='hidden' name='csrf_token' value='<?= $_SESSION['csrf_token'] ?>'>
// On submit, verify
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
die('CSRF token mismatch');
}Why it works: An attacker's site can force the browser to send cookies, but cannot read the CSRF token from your session, so their forged request fails the check.
CSRF authenticated user के browser को बिना उनकी मर्ज़ी के request भेजने पर मजबूर करता है, उनके existing session cookies का उपयोग करके।
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
die('CSRF token mismatch');
}Was this answer clear?