Wordpress - Why should I use the esc_url?

If you check the documentation on Data Validation it has following to say about the function:

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 [...], eliminates invalid characters, and removes dangerous characters.

There you have it — practical security benefit. Valid protocol, no murky characters.

The answer about necessity is firmly yes. Escaping output is the most basic security practice.


well, all user input should be sanitized... If the url you inject is not user input (e.g. site setting by someone you fully trust, hardcoded values) then you may relief yourself from esc-url.

but if I could inject that url to your site, i could easily inject js code, or redirection code... or even server side code in some situations.

this can lead to session hijacking and your users accounts being stolen and other bad options.

Edit:

In your example esc_url( home_url( '/' ) );
it operated on a semi-hardcoded value! therefore esc_url can be eliminated.
That said I still don't see why bother distinctions between when there is a threat and when there is not and generally would suggest to keep esc_url() for every value.


Another things must be keep in your head about esc_url() is for something like <a href="SANITIZE_THIS_URL">your_text</a>.if you’re going to use the URL in your HTML output, like a href attribute for a link, or a src attribute for an image element, you should use esc_url().

esc_url_raw()is for other cases where you want a clean URL, but you don’t want HTML entities to be encoded. So any non-HTML usage (DB, redirect) would use this.

The esc_url_raw() function will do pretty much the same as esc_url(), but it will not decode entities, meaning it will not replace & with &#038 and so on. As Mark pointed out, it’s safe to use esc_url_raw() in database queries, redirects and HTTP functions, such as `wp_remote_get()' for more info about esc_url_raw()

Tags:

Security