Question

http://core.trac.wordpress.org/browser/trunk/wp-includes/formatting.php#L2239

I'm confused about when should either of them be used.

Assuming I have this URL: http://site.com/?getsomejavascript=1, which is dynamically generated javascript:

  • if I include the script with esc_url(add_query_arg('apples', 420)), I get http://site.com/?getsomejavascript=1&apples=420 and it breaks because of those #038; references

  • if I use esc_url_raw(add_query_arg('apples', 420)) I get the correct URL: http://site.com/?getsomejavascript=1&apples=420

but in the documentation I find out that esc_url_raw should only be used to escape URLs inserted in the database...

Was it helpful?

Solution

From the Codex entry for Data Validation: URLs:

esc_url( $url, (array) $protocols = null ) (since 2.8)

Always use esc_url when sanitizing URLs (in text nodes, attribute nodes or anywhere else). Rejects URLs that do not have one of the provided whitelisted protocols (defaulting to http, https, ftp, ftps, mailto, news, irc, gopher, nntp, feed, and telnet), eliminates invalid characters, and removes dangerous characters. Deprecated since 3.0: clean_url() This function encodes characters as HTML entities: use it when generating an (X)HTML or XML document. Encodes ampersands (&) and single quotes (') as numeric entity references (&, ').

esc_url_raw( $url, (array) $protocols = null ) (since 2.8)

For inserting an URL in the database. This function does not encode characters as HTML entities: use it when storing a URL or in other cases where you need the non-encoded URL. This functionality can be replicated in the old clean_url function by setting $context to db.

So, the primary differences appear to be:

  1. esc_url() encodes HTML entities, while esc_url_raw() does not
  2. esc_url() is intended for output, while esc_url_raw() is intended for database storage

EDIT:

Since you are either hard-coding (or saving/storing separately) the actual URL from the query string, and then appending the query string via [add_query_arg()][2], might it be better to escape your appended query string via esc_js(), rather than esc_url()?

For example:

add_query_arg( esc_js( 'apples' ), esc_js( '420' ), $myurl )
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top