CSRF Protection in PHP
What is CSRF?
Cross-Site Request Forgery (CSRF) is a web security vulnerability that allows an attacker to trick authenticated users into executing unwanted actions on a website where they're currently logged in. The attack works by exploiting the trust that a website has in a user's browser.
How CSRF Attacks Work
- User logs into legitimate website A and receives a session cookie
- User visits malicious website B while still logged into A
- Website B contains code that makes a request to website A
- The browser automatically includes the session cookie
- Website A processes the request thinking it's legitimate
CSRF Protection Methods in PHP
1. Token-Based Protection Using Hidden Input
This is the most common method. Here's how to implement it:
// In your session initialization (e.g., at login) session_start(); if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); } // In your form function generateFormWithCSRFToken() { return '<form method="POST" action="/submit"> <input type="hidden" name="csrf_token" value="' . $_SESSION['csrf_token'] . '"> <!-- rest of your form fields --> <input type="submit" value="Submit"> </form>'; } // In your form processing function validateCSRFToken() { if (!isset($_POST['csrf_token']) || !isset($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) { die('CSRF token validation failed'); } return true; }
2. CSRF Protection Using Custom Headers
This method uses AJAX requests with custom headers:
// PHP Backend session_start(); if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); } // Validate the token if ($_SERVER['REQUEST_METHOD'] === 'POST') { $headers = getallheaders(); if (!isset($headers['X-CSRF-Token']) || !hash_equals($_SESSION['csrf_token'], $headers['X-CSRF-Token'])) { http_response_code(403); die('CSRF token validation failed'); } } // JavaScript Frontend const csrfToken = '<?php echo $_SESSION["csrf_token"]; ?>'; fetch('/api/endpoint', { method: 'POST', headers: { 'X-CSRF-Token': csrfToken, 'Content-Type': 'application/json' }, body: JSON.stringify(data) });
3. Double Submit Cookie Pattern
This method involves sending the token both as a cookie and as a request parameter:
// Set both cookie and session token session_start(); $token = bin2hex(random_bytes(32)); $_SESSION['csrf_token'] = $token; setcookie('csrf_token', $token, [ 'httponly' => true, 'secure' => true, 'samesite' => 'Strict' ]); // Validation function function validateDoubleSubmitToken() { if (!isset($_COOKIE['csrf_token']) || !isset($_POST['csrf_token']) || !isset($_SESSION['csrf_token'])) { return false; } return hash_equals($_COOKIE['csrf_token'], $_POST['csrf_token']) && hash_equals($_SESSION['csrf_token'], $_POST['csrf_token']); }
4. SameSite Cookie Attribute
Modern applications can also use the SameSite cookie attribute as an additional layer of protection:
// Set cookie with SameSite attribute session_start(); session_set_cookie_params([ 'lifetime' => 0, 'path' => '/', 'domain' => $_SERVER['HTTP_HOST'], 'secure' => true, 'httponly' => true, 'samesite' => 'Strict' ]);
Best Practices for CSRF Protection
-
Token Generation
- Use cryptographically secure random number generators
- Make tokens sufficiently long (at least 32 bytes)
- Generate new tokens for each session
function generateSecureToken($length = 32) { return bin2hex(random_bytes($length)); }
-
Token Validation
- Use timing-safe comparison functions
- Validate token presence and value
- Implement proper error handling
function validateToken($userToken, $storedToken) { if (empty($userToken) || empty($storedToken)) { return false; } return hash_equals($storedToken, $userToken); }
-
Form Implementation
- Include tokens in all forms
- Implement automatic token injection
- Handle token rotation
class CSRFProtection { public static function getTokenField() { return sprintf( '<input type="hidden" name="csrf_token" value="%s">', htmlspecialchars($_SESSION['csrf_token']) ); } }
Framework-Specific Protection
Many PHP frameworks provide built-in CSRF protection:
Laravel Example
// In your session initialization (e.g., at login) session_start(); if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); } // In your form function generateFormWithCSRFToken() { return '<form method="POST" action="/submit"> <input type="hidden" name="csrf_token" value="' . $_SESSION['csrf_token'] . '"> <!-- rest of your form fields --> <input type="submit" value="Submit"> </form>'; } // In your form processing function validateCSRFToken() { if (!isset($_POST['csrf_token']) || !isset($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) { die('CSRF token validation failed'); } return true; }
Symfony Example
// PHP Backend session_start(); if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); } // Validate the token if ($_SERVER['REQUEST_METHOD'] === 'POST') { $headers = getallheaders(); if (!isset($headers['X-CSRF-Token']) || !hash_equals($_SESSION['csrf_token'], $headers['X-CSRF-Token'])) { http_response_code(403); die('CSRF token validation failed'); } } // JavaScript Frontend const csrfToken = '<?php echo $_SESSION["csrf_token"]; ?>'; fetch('/api/endpoint', { method: 'POST', headers: { 'X-CSRF-Token': csrfToken, 'Content-Type': 'application/json' }, body: JSON.stringify(data) });
Common Pitfalls to Avoid
- Don't use predictable tokens
- Don't store tokens in JavaScript variables accessible globally
- Don't skip CSRF protection for AJAX requests
- Don't rely solely on checking the Referer header
- Don't use the same token for multiple forms
CSRF protection is crucial for web application security. While there are multiple approaches to implementing CSRF protection, the token-based approach using hidden form fields remains the most widely used and reliable method. Remember to combine different protection methods for enhanced security and always follow security best practices when implementing CSRF protection in your PHP applications.
Remember that CSRF protection should be part of a broader security strategy that includes proper session management, secure cookie handling, and input validation.
The above is the detailed content of CSRF Protection in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.
