0

I have the following PHP code inside a Wordpress template that gets the user search query text and insert it into a string:

$name = sprintf( esc_html__( 'Search Results for: %s'),  get_search_query());

The line as mentioned works, and the result is something like:

"Search Results for Doggy Bags"

What I don't understand is, why does it work? Shouldn't esc_html__() run first before sprintf() has had the chance to replace the placeholder (%s) inside the former function to the search query term?

Thanks,

coco puffs
  • 1,040
  • 12
  • 8
  • You might find some of the answers to http://stackoverflow.com/questions/1514676/is-php-compiled-or-interpreted relevant – EvilEpidemic Aug 22 '16 at 02:21

1 Answers1

1

You are correct. esc_html__() runs first and returns its output to sprintf().

The esc_html__() function returns the translation of Search Results for: %s and escapes it for safe use in HTML output.

Its output if there are no defined translations for this string is Search Results for: %s. Effectively, it becomes:

sprintf("Search Results for: %s",get_search_query());

and then:

sprintf("Search Results for: %s","Doggy Bags");

Finally, it becomes:

Search Results for: Doggy Bags

rationalboss
  • 5,330
  • 3
  • 30
  • 50
  • Thanks. Based on this order of events, doesn't it mean that the value of `get_search_query()` doesn't get the `esc_html()` treatment, potentially leading to a security hole? – coco puffs Aug 22 '16 at 18:30
  • That seems right. You can prove this by specifying HTML tags in your search query. – rationalboss Aug 22 '16 at 23:15