Validating GET and POST Parameters
To prevent CSRF attacks, it's essential to validate user input, not only in cookies but also in GET and POST parameters. This can be achieved by matching submitted values against stored values or expected data types.
Checking the HTTP Referer Header
The HTTP Referer header indicates the URL of the page that made the request. While its value is not always reliable, it can provide additional security by checking that the referring page matches a trusted domain.
Implementation in Kohana Framework
In Kohana framework, you can retrieve the Referer header using:
$referrer = $this->request->headers['referer'];
Validating One-Time Tokens
A more secure approach involves using a one-time token that is generated for each session and associated with a specific action. This token should be:
Example Implementation:
// On the confirmation page $token = md5(uniqid()); // Generate and store token // On the action page if (isset($_POST['token']) && $_POST['token'] === $token) { // Validate token and perform action ... } else { // CSRF attack detected }
Additional Tips
The above is the detailed content of How Can PHP Developers Effectively Prevent Cross-Site Request Forgery (CSRF) Attacks?. For more information, please follow other related articles on the PHP Chinese website!