Learn how to disable the CSRF protection of a form with a model in Symfony 1.4

How to disable the CSRF protection/verification for a Form in Symfony 1.4

The csrf token provides protection for your forms against the Cross-Site Request Forgery (CSRF), an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. In some projects, due to the lack of symfony to define multiple forms of the same entity in a view, you will end up designing your form manually with HTML (this means that no any sfForm instance has been rendered on the view and there's no CSRF protection enabled), however using the default binder of symfony to store the information from an array, for example:

<?php

// Some data that will be binded from an array to the model
$formData = array(
    "title" => "Hello World",
    "content" => "Bla bla bla ..."
);

// Define the form
$this->form = new SomeModelForm();
 
// Deal with the request
if ($request->isMethod('post'))
{
    $this->form->bind($formData);

    if ($this->form->isValid())
    {
        // Rest of logic
    }
}

The bind process, if the data matches with the defined model, will succesfully be binded, however you will see an exception that specifies that the form is invalid because the _csrf_token field isn't available (as long as the csrf protection is enabled in your project):

500 Internal Server Error: _csrf_token [Required.]

In such case, if you know what you're doing and understand what it means to disable the _csrf_token, for example, where CSRF is unneeded, rather api keys or something like that is used, you will be able to disable it not globally but specifically on every form that you need with a single line of code.

Disable CSRF token in a single form

To disable CSRF protection from your form, simply call the getValidor method from it, that expects as first argument the name of the CSRF token (generated automatically from the method getCSRFFieldName) and from the returned value, call the setOption method from it defining the required option to false.

What you are basically doing is setting the _csrf_token field to not required, so your form will be valid and that's it:

<?php

// Define the form
$this->form = new SomeModelForm();

// Disable CSRF protection
$this->form->getValidator($form->getCSRFFieldName())->setOption('required', false);

// Rest of logic, where the form will be valid 

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors