My plugin has a tab in the CP. On that tab is a form. What's the way for PHP to generate a CSRF token that can be output to the form with echo?

EDIT to document the final answer

$token = craft()->request->getCsrfToken();
$out .= <<<MYFORM
   <form action="#" method="post">
      <input type='hidden' name="CRAFT_CSRF_TOKEN" value='$token'>
return $out;

And make sure that /craft/config/general.php includes this:

return array(
       'enableCsrfProtection' => true,
  • Definitely don't use echo. If you want to pass data back to your Twig template, there are several other (much better) ways to do it. Most of the time you'll want to use a Variable defined by your plugin.
    – Lindsey D
    Commented May 28, 2015 at 18:55
  • @LindseyD Yes, sorry, I'm doing that, I think.
    – kr37
    Commented May 28, 2015 at 20:20

1 Answer 1


Maybe try craft()->request->getCsrfToken(), see if that does it?


Sorry, misunderstood the question, since you are saying your plugin has a CP section then i'm assuming you're actually looking for a twig way to output the CSRF input, not so much a PHP way. To output the CRSF input in your template simply do {{ getCsrfInput() }}

  • Thank you, that works, in conjunction with <input type='hidden' name="CRAFT_CSRF_TOKEN" value='{craft()->request->getCsrfToken()}'>
    – kr37
    Commented May 28, 2015 at 20:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.