5.3. Improper Use of t

It's also possible to use the t function and have insecure data in the result. The t function will only sanitize data in placeholders and specifically with the @ or % placeholder. So how can you make it unsafe?

The next few snippets are examples of how not to use the t function. Again, study these for how bad they are and not as examples to copy.

One example of text that should be sent through the t function comes from the Vulnerable module:

$output = 'Information about users with '. $user_search .' in their
  name<br>.';

That example doesn't use the t function at all. A naive implementation of the t function might look like this.

$output = t('Information about users with '. $user_search .' in
  their name<br>.');

Simply wrapping the string in the t function provides basically no benefit. The string still passes straight through, creating an XSS vulnerability, and the translation file would have to contain every possible value of $user_search in order to translate the data. Creating such a translation file is practically impossible because the user can search for any combination of letters and numbers of an arbitrary length. So to fix the problem for translators, a developer might alter the code to use a placeholder.

$output = t('Information about users with !search in their name<br>.',
  array('!search' =>  $user_search));

The string can now be reasonably translated, ...

Get Cracking Drupal®: A Drop in the Bucket now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.