Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 3.0.1 CSRF token present but invalid

Tags:

forms

php

symfony

I am having this strange issue with a fresh Symfony 3.0.1 installation. I generated a new CRUD Controller with a Form PostType which contains an url and a title. Nothing fancy.

The form is rendered as expected. It contains both my url field and title field. Inside the form the hidden input field _token is also rendered.

When submitting this form, i am getting all the time the following error:

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

So the token is added to the form, it contains a value, i have a constant PHP session cookie value, it is just that this token invalid.

I have searched for other answers but the similar questions are all caused by the absence of a _token input.

This problem also occurs in Symfony 3.0.2/3.0.3.

like image 289
joostvandriel Avatar asked Feb 04 '16 18:02

joostvandriel


3 Answers

In my case it was that the var/sessions/ folder wasn't writable. The default is var/sessions which is set at config.yml.

session:
    # http://symfony.com/doc/current/reference/configuration/framework.html#handler-id
    handler_id:  session.handler.native_file
    save_path:   "%kernel.root_dir%/../var/sessions/%kernel.environment%"

Make sure you have var/ folders writable.

chmod 775 -R var/sessions/
chmod 775 -R var/log/
chmod 775 -R var/cache/
like image 100
Pedro Casado Avatar answered Nov 07 '22 23:11

Pedro Casado


I just had a similar issue with Symfony 3.2

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

After hours, we finally found the issue was related to session.cookie_secure (https):

Our production environment uses https, thus forces cookies to be secured over https. The dev environment used http. After moving the dev from HTTP to HTTPS, problem was fixed.

like image 22
Shrihari Avatar answered Nov 08 '22 01:11

Shrihari


I'm using Symfony 3.2.1 and it's working on one machine but not the other. No idea why.

@Shrihari his answer led me to the following solution.

My project also has cookie_secure: true. I updated config_dev.yml and added cookie_secure: false to the file.

framework:
    session:
        cookie_secure: false

This worked for me.

like image 22
ar34z Avatar answered Nov 08 '22 00:11

ar34z