0

We have an admin form that has two text fields ('pattern' and 'host'). In a ControllerClass we have to use the input to perform some logic.

How would we properly sanitize the input from the two text fields on save of text field values and when retrieving the value in a controller class?

Current code:

class MyModule extends ProviderPluginBase {
  public function _some_function($input) {
    $mymodule_config = \Drupal::config('mymodule.settings');
    $host = $mymodule_config->get('host');
    $pattern = $mymodule_config->get('pattern');

    /* we will need to use the $host and $pattern */
}

We initially thought that HTML::escape would work, but that is for output. Not sure how to sanitize the input.

Example of what we tried for the controller class:

$escapted_value = _some_sanitization_function($pattern);

When saving the text field value:

public function submitForm(array &$form, FormStateInterface $form_state) {
  $config = $this->config('mymodule.settings');
  $config
    ->set('pattern', _some_sanitization_function($form_state->getValue('pattern'))
    ->set('host', _some_sanitization_function($form_state->getValue('host'))
    ->save();
}
  • 1
    Always escape on output, not input. If the text is rendered in a template as a variable, that will happen automatically. The docs are here: drupal.org/docs/8/security/writing-secure-code-for-drupal-8 – Clive Mar 19 '18 at 17:37
  • @Clive looks like I was confusing the purpose of the HTML::escape. What would be the _some_sanitization_function used to sanitize the input? – usernameabc Mar 19 '18 at 18:02
  • 2
    You don’t sanitise input, you always want that to be raw. Obviously use the DB abstraction layer to prevent sql injection if you’re executing queries with this input (in your code example hat doesn’t apply, you’re at a higher level of abstraction and the underlying code will take care of it), but other than that you only need to consider output. The linked docs cover it in full – Clive Mar 19 '18 at 18:02
  • @Clive that is what I thought, but when I submitted a patch to the Drupal community for a module, it was mentioned that a variables that was fetched from the $config needs to be sanitized. As such, I was searching for correct way to do that. – usernameabc Mar 19 '18 at 18:09
  • 1
    Yes it needs to be filtered for xss before being rendered. If you output it as a twig variable, {{ foo }}, that’s all you need. Honestly, read the linked docs they cover this very well – Clive Mar 19 '18 at 18:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.