[php] The CSRF token is invalid. Please try to resubmit the form

I'm getting this error message every time I try to submit the form:

The CSRF token is invalid. Please try to resubmit the form

My form code is this:

<form novalidate action="{{path('signup_index')}}" method="post" {{form_enctype(form)}} role="form" class="form-horizontal">
    <div class="form-group">
        {{ form_label(form.email, 'Email', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
        {{ form_widget(form.email, {'attr': {'class': 'col-md-2'}}) }}
        {{ form_errors(form.email) }}
    </div>

    <div class="form-group">
        {{ form_label(form.nickname, 'Nickname', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
        {{ form_widget(form.nickname, {'attr':{'class': 'col-md-2'}}) }}
        {{ form_errors(form.nickname, {'attr': {'class': 'col-md-3'}}) }}
    </div>
    <div class="form-group">
        {{ form_label(form.password, 'password', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
        {{ form_widget(form.password, {'attr': {'class': 'col-md-2'}}) }}
        {{ form_errors(form.password, {'attr': {'class': 'col-md-3'}}) }}
    </div>

    <div class="form-group">
        {{ form_label(form.password_repeat, 'Repeat password', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
        {{ form_widget(form.password_repeat, {'attr':{'class': 'col-md-2'}}) }}
        {{ form_errors(form.password_repeat, {'attr': {'class': 'col-md-3'}}) }}
    </div>
    <div class="form-group">
        <div class="col-md-1 control-label">
        <input type="submit" value="submit">
    </div>

    </div>
</form>

Any ideas?

This question is related to php symfony twig

The answer is


You need to remember that CSRF token is stored in the session, so this problem can also occur due to invalid session handling. If you're working on the localhost, check e.g. if session cookie domain is set correctly (in PHP it should be empty when on localhost).


This happens because forms by default contain CSRF protection, which is not necessary in some cases.

You can disable this CSRF protection in your form class in getDefaultOptions method like this:

// Other methods omitted

public function getDefaultOptions(array $options)
{
    return array(
        'csrf_protection' => false,
        // Rest of options omitted
    );
}

If you don't want to disable CSRF protection, then you need to render the CSRF protecion field in your form. It can be done by using {{ form_rest(form) }} in your view file, like this:

<form novalidate action="{{path('signup_index')}}" method="post" {{form_enctype(form)}} role="form" class="form-horizontal">
    <!-- Code omitted -->

    <div class="form-group">
        <div class="col-md-1 control-label">
            <input type="submit" value="submit">
        </div>

    </div>
    {{ form_rest(form) }}
</form>

{{ form_rest(form) }} renders all fields which you haven't entered manually.


I had this issue with a weird behavior: clearing the browser cache didn't fix it but clearing the cookies (that is, the PHP session ID cookie) did solve the issue.

This has to be done after you have checked all other answers, including verifying you do have the token in a hidden form input field.


In case you don't want to use form_row or form_rest and just want to access value of the _token in your twig template. Use the following:

<input type="hidden" name="form[_token]" value="{{ form._token.vars.value }}" />

I had this error recently. Turns out that my cookie settings were incorrect in config.yml. Adding the cookie_path and cookie_domain settings to framework.session fixed it.


If you have converted your form from plain HTML to twig, be sure you didn't miss deleting a closing </form> tag. Silly mistake, but as I discovered it's a possible cause for this problem.

When I got this error, I couldn't figure it out at first. I'm using form_start() and form_end() to generate the form, so I shouldn't have to explicitly add the token with form_row(form._token), or use form_rest() to get it. It should have already been added automatically by form_end().

The problem was, the view I was working with was one that I had converted from plain HTML to twig, and I had missed deleting the closing </form> tag, so instead of :

{{ form_end(form) }}

I had:

</form>
{{ form_end(form) }}

That actually seems like something that might throw an error, but apparently it doesn't, so when form_end() outputs form_rest(), the form is already closed. The actual generated page source of the form was like this:

<form>
    <!-- all my form fields... -->
</form>
<input type="hidden" id="item__token" name="item[_token]" value="SQAOs1xIAL8REI0evGMjOsatLbo6uDzqBjVFfyD0PE4" />
</form>

Obviously the solution is to delete the extra closing tag and maybe drink some more coffee.


In addition to others' suggestions you can get CSRF token errors if your session storage is not working.

In a recent case a colleague of mine changed 'session_prefix' to a value that had a space in it.

session_prefix: 'My Website'

This broke session storage, which in turn meant my form could not obtain the CSRF token from the session.


I had the same error, but in my case the problem was that my application was using multiple first-level domains, while the cookie was using one. Removing cookie_domain: ".%domain%" from framework.session in the config.yml caused cookies to default to whatever domain the form was on, and that fixed the problem.


Before your </form> tag put:

{{ form_rest(form) }}

It will automatically insert other important (hidden) inputs.


In my case I got a trouble with the maxSize annotation in the entity, so I increased it from 2048 to 20048.

 /**
 * @Assert\File(
 *     maxSize = "20048k",
 *     mimeTypes = {"application/pdf", "application/x-pdf"},
 *     mimeTypesMessage = "Please upload a valid PDF"
 * )
 */
private $file;

hope this answer helps!


Also you can see this error message when your form has a lot of elements.

This option in php.ini cause of problem

; How many GET/POST/COOKIE input variables may be accepted
 max_input_vars = 1000

Problem is that _token field misses PUT (GET) request, so you have to increase value.

Also, it concerns a big files. Increasing the

upload_max_filesize

option will solve problem.


This seems to be an issue when using bootstrap unless you are rendering the form by {{ form(form)}}. In addition, the issues seems to only occur on input type="hidden". If you inspect the page the with the form, you'll find that the hidden input is not part of the markup at all or it's being rendered but not submitted for some reason. As suggested above, adding {{form_rest(form)}} or wrapping the input like below should do the trick.

<div class="form-group">
    <input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">
</div>

I hade the same issue recently, and my case was something that's not mentioned here yet:

The problem was I was testing it on localhost domain. I'm not sure why exactly was this an issue, but it started to work after I added a host name alias for localhost into /etc/hosts like this:

127.0.0.1        foobar

There's probably something wrong with the session while using Apache and localhost as a domain. If anyone can elaborate in the comments I'd be happy to edit this answer to include more details.


I faced a similar issue. After ensuring the token field was actually rendered (see accepted answer) I checked my cookies. There were 2(!) cookies for the domain in my Chrome browser, apparently because I was running the application on the same domain as another app, but with a different port (i.e. mydomain.com set the original cookie while the buggy app was running on mydomain.com:123) Now apparently Chrome sent the wrong cookie so the CSRF protection was unable to link the token to the correct session.

Fix: clear all the cookies for the domain in question, make sure you don't run multiple applications on the same domain with differing ports.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to symfony

Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2 The CSRF token is invalid. Please try to resubmit the form What is the difference between .yaml and .yml extension? How can I use break or continue within for loop in Twig template? Running Composer returns: "Could not open input file: composer.phar" Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings Symfony - generate url with parameter in controller Call PHP function from Twig template

Examples related to twig

The CSRF token is invalid. Please try to resubmit the form How can I use break or continue within for loop in Twig template? Call PHP function from Twig template Check if inputs form are empty jQuery Counting the number of elements in array How to use absolute path in twig functions symfony 2 twig limit the length of the text and put three dots Find substring in the string in TWIG How to include CSS file in Symfony 2 and Twig? Twig ternary operator, Shorthand if-then-else