How to Prevent CSRF in PHP: Simple and Effective Methods
CSRF token stored in the user's session and include it in forms. On form submission, verify the token matches the session token before processing the request.Why This Happens
CSRF (Cross-Site Request Forgery) happens when a malicious website tricks a user's browser into sending unwanted requests to a trusted site where the user is logged in. This happens because browsers automatically send cookies with requests, so the trusted site thinks the request is legitimate.
<?php // Broken code without CSRF protection if ($_SERVER['REQUEST_METHOD'] === 'POST') { $username = $_POST['username']; // Process form without verifying request origin echo "User " . htmlspecialchars($username) . " updated."; } ?> <form method="POST"> <input type="text" name="username" /> <button type="submit">Update</button> </form>
The Fix
Generate a unique CSRF token when the form loads and store it in the session. Include this token as a hidden field in the form. When the form is submitted, check if the token matches the one in the session. If it does not match, reject the request.
<?php session_start(); // Generate CSRF token if not set if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); } if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) { die('CSRF token validation failed'); } $username = $_POST['username']; echo "User " . htmlspecialchars($username) . " updated safely."; } ?> <form method="POST"> <input type="text" name="username" /> <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>" /> <button type="submit">Update</button> </form>
Prevention
Always use CSRF tokens for any form or state-changing request in your PHP applications. Store tokens securely in sessions and verify them on every POST request. Avoid relying on cookies alone for security. Use HTTPS to protect tokens in transit. Consider using frameworks or libraries that handle CSRF protection automatically.
Related Errors
Other common security issues related to CSRF include:
- Session fixation: Attackers fix a user's session ID to hijack their session.
- Cross-site scripting (XSS): Malicious scripts steal tokens or cookies.
- Missing input validation: Allows injection attacks.
Fix these by using secure session management, input sanitization, and proper token validation.