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

PhpSymfonyTwig

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

You need to add the _token in your form i.e

{{ form_row(form._token) }}

As of now your form is missing the CSRF token field. If you use the twig form functions to render your form like form(form) this will automatically render the CSRF token field for you, but your code shows you are rendering your form with raw HTML like <form></form>, so you have to manually render the field.

Or, simply add {{ form_rest(form) }} before the closing tag of the form.

>According to docs > > This renders all fields that have not yet been rendered for the given > form. It's a good idea to always have this somewhere inside your form > as it'll render hidden fields for you and make any fields you forgot > to render more obvious (since it'll render the field for you).

form_rest(view, variables)

Solution 2 - Php

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.

Solution 3 - Php

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.

Solution 4 - Php

Before your </form> tag put:

{{ form_rest(form) }}

It will automatically insert other important (hidden) inputs.

Solution 5 - Php

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.

Solution 6 - Php

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.

Solution 7 - Php

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.

Solution 8 - Php

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.

Solution 9 - Php

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.

Solution 10 - Php

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 }}" />

Solution 11 - Php

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!

Solution 12 - Php

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.

Solution 13 - Php

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.

Solution 14 - Php

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).

Solution 15 - Php

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFrancisco AlbertView Question on Stackoverflow
Solution 1 - PhpM Khalid JunaidView Answer on Stackoverflow
Solution 2 - PhpzalexView Answer on Stackoverflow
Solution 3 - Phpuser3577953View Answer on Stackoverflow
Solution 4 - PhpLkopoView Answer on Stackoverflow
Solution 5 - PhpBenoit DuffezView Answer on Stackoverflow
Solution 6 - PhpHenryView Answer on Stackoverflow
Solution 7 - PhpDon't PanicView Answer on Stackoverflow
Solution 8 - PhpMichaelView Answer on Stackoverflow
Solution 9 - PhpTeo.skView Answer on Stackoverflow
Solution 10 - PhpImran ZahoorView Answer on Stackoverflow
Solution 11 - PhpJorgeeadanView Answer on Stackoverflow
Solution 12 - PhplkoellView Answer on Stackoverflow
Solution 13 - PhpACJView Answer on Stackoverflow
Solution 14 - PhpIntolView Answer on Stackoverflow
Solution 15 - PhpkrompirView Answer on Stackoverflow