Built-in data validation function for URLs

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 ?

Read More

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);
}

Related posts

Leave a Reply

2 comments

  1. 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 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:

    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.