How I Fixed: CSRF Token Is Invalid

There’s an obvious fix, and a not so obvious fix to this problem – The CSRF Token Is Invalid. Please try to resubmit the form:

The CSRF Token Is Invalid. Please try to resubmit the form.

The ‘obvious’ fix is that you may very well have forgotten to add in:

To your twig form template file.

It’s easy to do, and we’ve all done it.

You may see this as:

Also, but as of Symfony 3 at leastform_rest is now added in to  form_end for free. It may have arrived earlier, but it’s late now, and I’m too tired to check.

Anyway, if that all works then perfect, and off you go.

However, the less obvious problem might be that your session directory is not writable by the web server user.

This just caught me out when setting up a new server.

I’d used Ansible to build my dev server, and then I’d also deployed a variant of my dev script to production.

However, somewhere along the way I’d boobed and created myself a  var/sessions directory, and also a  shared/var/sessions directory, and whilst the permissions where correct on one, they weren’t correct on the right one :/

Why might this be the case? Well, I deploy using Deployer, but I’d only just set that up to deploy to prod. During dev I simply work on the local VM – no deploy script needed. And at this stage I don’t have a staging box for  this project.

So yeah, make sure that whatever user your web server is running as –  www-data in this case – also has permissions to write to whichever directory you are storing your session data in.

You can find this directory by looking in  config.yml :



Published by

Code Review

Code Review

CodeReviewVideos is a video training site helping software developers learn Symfony faster and easier.

3 thoughts on “How I Fixed: CSRF Token Is Invalid”

  1. hi;
    thanks for this article .
    i hav the same error in my form reseting password (FOSUserBundle) : The CSRF token is invalid. Please try to resubmit the form.

    this is the HTML rendered:

    the code in twig :

    all my other forms work fine except this one

Leave a Reply

Your email address will not be published. Required fields are marked *