Justin
Justin

Reputation: 45340

Best ways to protect against CSRF attacks in PHP

What is the best way to protect again CSRF attacks in PHP.

It has been recommend to use form tokens, so basically generate a random value and store it in a hidden field. Then also store this random value in the users session.

Finally in the form action, make sure the session and form token match.

if($_SESSION['token'] !== $_POST['token']) {
   die("bad... spanking...");
}

Is there a better/easier way, as this requires a lot of code modification in my application (lots of forms and actions).

Upvotes: 1

Views: 1323

Answers (1)

Mike Samuel
Mike Samuel

Reputation: 120496

No. To protect against CSRF, you need to make sure you only trust credentials that are automatically appended to requests (like cookies) when you have reason to believe that the user actually submitted your form. The only way to do that is to have the form carry some kind of secret that the server uses to authorize processing.

If you use a framework or library to compose your form it might help by generating the random number, setting the cookie or session property, and adding the hidden input to your form but those three steps do need to happen.

Upvotes: 2

Related Questions