4

Example Drupal 6 query:

$q = db_query("SELECT id FROM {table} WHERE no = %d AND name LIKE '%%%s%%'", 
               $_GET['something'], $_GET['something_else']);

Example Drupal 7 query:

$q = new EntityFieldQuery();
$q->entityCondition('entity_type', 'some_entity')
  ->propertyCondition('id', $_GET['something'])
  ->fieldCondition('field_name', 'value', '%'.$_GET['something_else'].'%', 'like');

The $_GET values could be anything the user can technically send. Should additional steps be taken like using PHP-s is_numeric function for numbers and db_escape_string() for strings to make sure the input wont cause any harm or are the queries already secure? Does the same count for other Database API functions?

5

It depends what you mean by "secure." If your goal is just to block sql injection then yes, that's it :) For Drupal 6, be sure you are using the right placeholder based on db_query docs:

Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose in '') and %%.

And be sure that you enclose the %s placeholder in ''. Failure to match these properly can lead to sql injection.

Drupal 7 takes care of that for you. Even if you use the Drupal 7 db_query you use placeholders like :name and it will figure out the data type and take care of proper filtering/substitution/quoting for you.

The other security related topic for queries is the node access system. In Drupal 6 you should use db_rewrite_sql. In Drupal 7 be sure to use $query->addTag('node_access'); if you are querying for nodes.

This system of preventing SQL Injection as part of the API is, in my opinion, one of the great features of Drupal. Similar functions that perform both functional and security features are the t() and l() function which will prevent XSS when they are used properly.

  • Thanks! That covers what I wanted to know and confirms the bits of information I managed to obtain from other sources. – Madis Jan 13 '12 at 15:54

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.