Difference between esc_url() and esc_url_raw()

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 )

Leave a Comment