PHP XSRF Protection

This class provides a simple method of protecting form submission from common Cross Site Request Forgery (XSRF) attacks.

Protection is accomplished by adding a randomised hidden field to forms that are checked when the form is processed. If the hidden field doesn't exist, or is modified then the request should be rejected.

The method used is stateless and does not require any session management to be used. This allows the request to be easily handled by a load balanced cluster of frontends that don't share session information.

Protection against replay attacks can also be provided using this same method, but requiring session local storage which makes this stateful, and requires distributed session management if multiple web servers are being used.

[ Source | Issues | Download Source ]

Sample Code

  1. <?php
  3. include "XsrfProtection.php";
  5. // Create the protection object
  6. $prot = new XsrfProtection();
  7. // Set a secret key. This should really be secret, but must be shared between
  8. // all your frontends that will be handling this type of request.
  10. // Set some user data. This would normally be the logged in user or some other
  11. // identifying field.
  12. $prot->SetUserData("dparrish");
  13. // Set the URL field
  14. $prot->SetUrl("");
  15. // Set the maximum age of tokens. The default is 1 hour.
  16. $prot->SetTimeout(3600);
  17. // Use the session cache to prevent replay attacks.
  18. $prot->SetStateful();
  21. if (isset($_REQUEST['test'])) {
  22.   // Validate the submitted form token.
  23.   $ret = $prot->Validate($_POST);
  24.   if ($ret != XsrfProtection::kCheckSuccess{
  25.     // There was an error, print out the reason. This is not a good idea in
  26.     // production, but works for an example.
  27.     print "XSRF detected, validation failure "$prot->Error()"\n";
  28.     return;
  29.   }
  30.   // All good, print something out and return
  31.   print "Test value: "$_REQUEST['test'];
  32.   return;
  33. }
  35. // Generate a very basic form that has XSRF protection.
  36. ?>
  37. <form method='post'>
  38. <input type='text' name='test' value='foobar'>
  39. <input type='submit' name='doit' value='Submit'>
  40. <?=$prot->ProtectionField()?>
  41. </form>
Subpages (1): Manual