5

Does PHP have its own version of the Rails authenticity token?

<meta name="csrf-token" content="<%= form_authenticity_token %>" />
<meta name="csrf-param" content="authenticity_token" />

If not, what is the best way to achieve the same functionality?

EliTheDawg
  • 1,157
  • 15
  • 36
  • This is for CSRF protection. But CSRF protection can nowadays be done without such tokens, just with special cookie parameters. You may want to take a look at https://github.com/delight-im/PHP-Auth which does that automatically. – caw Oct 21 '16 at 21:32

1 Answers1

8

When outputting to form:

$token = md5(time() . rand(1,100));
$_SESSION['token'] = $token;

<input type='hidden' name='token' value='<?=$token;?>'/>

After POST:

if(empty($_POST['token']) || $_POST['token'] !== $_SESSION['token']){
  exit("Bad token!");
}
unset($_SESSION['token']);
Mārtiņš Briedis
  • 17,396
  • 5
  • 54
  • 76
  • How would you rate that against using something like recaptcha? I noticed that twitter does not use a captcha for their register forms <- hence where I got the idea... – EliTheDawg Feb 24 '11 at 22:07
  • A token protects from CSRF attacks, but captcha blocks out non-human users (and protects from CSRF). Which one are you looking for? – Mārtiņš Briedis Feb 24 '11 at 22:11
  • Both... How does twitter get away with it? – EliTheDawg Feb 24 '11 at 22:13
  • 1
    @mtokoly They could be also using services like Akismet to match IPs and see if it matches – allenskd Feb 24 '11 at 22:31
  • @Booski It looks like `$token = bin2hex(openssl_random_pseudo_bytes(16));` is a better solution if you want a random token: http://stackoverflow.com/questions/18910814/best-practice-to-generate-random-token-for-forgot-password/29137661#29137661 Using `!isset` instead of `empty` and comparing with `==` instead of `===` should be enough also. If you really want to prevent CSRF, you should check `if(!isset($_SESSION['token']))` before generating a token for your session, so a third-party website can't create a new token for your website if it already exists and invalidate the old one. – baptx Aug 14 '16 at 16:09