Use esc_url( $url )
for URLs that should be displayed and esc_url_raw( $url )
if the URL should be sent to the database.
- The first will replace bare ampersands
&
with&
. - The second is a wrapper for the first; it will just suppress the escaping of ampersands.
- Both functions will check the protocol. See
wp_allowed_protocols()
for the list:
'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn', 'tel', 'fax', 'xmpp'
So an URL likejavascript:alert("Hacked!");
will not get through.
These functions are not exactly validators. They sanitize the value. But you should use them whenever you have an URL to save or to display.
There is also wp_validate_redirect( $location, $default )
.
$location
is an URL here and $default
a fallback URL if the first value doesn’t validate. From its doc block:
Validates a URL for use in a redirect.
Checks whether the $location is using an allowed host, if it has an absolute
path. A plugin can therefore set or remove allowed host(s) to or from the list.
Note the allowed hosts do not include all (sub) domains of a multi-site installation. No idea why.