3

Do I need to sanitize $userinput in this code, Or is it done by Drupal?

$nids = \Drupal::entityQuery('node')
  ->condition('type','my_node_type')
  ->condition('field_myfield', $userinput)
  ->execute();

In my case, $userinput is a path parameter from the .routing.yml file.

If necessary, how do I sanitize it? I found RequestSanitizer::sanitize(). Is that enough to protect against SQL injections?

1 Answer 1

3

As shown in Writing secure code for Drupal / Use the database abstraction layer to avoid SQL injection attacks, it's not necessary to sanitize user input used in the condition() method, as long as the user input isn't used to select the operator to apply. This means that the code shown in the question is fine, but the following code is not.

\Database::getConnection()
  ->select('table', 't')
  ->condition('t.field', $value, $userInput)
  ->execute();

What reported in that documentation is for the database classes, but it's also valid for the methods exposed from the instance returned by \Drupal::entityQuery().

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.