I have a front-end form where people can submit their website URL.
I’m actually verifying URLs in WordPress with a PHP function and I would like to know if there is a built-in function that allows me to do this ?
This is the function that I am actually using :
function validateURL($URL) {
$v = "/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i";
return (bool)preg_match($v, $URL);
}
Use
esc_url( $url )
for URLs that should be displayed andesc_url_raw( $url )
if the URL should be sent to the database.&
with&
.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 like
javascript: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:Note the allowed hosts do not include all (sub) domains of a multi-site installation. No idea why.
There isn’t a function that validates a URL, just one that sanitizes a string for use within a URL (
sanitize_title
).There’s a PHP filter that will validate URLs:
FILTER_VALIDATE_URL
.