valid_url

Definition

valid_url($url, $absolute = FALSE)
includes/common.inc, line 1183

Description

Verify the syntax of the given URL.

This function should only be used on actual URLs. It should not be used for Drupal menu paths, which can contain arbitrary characters. Valid values per RFC 3986.

Parameters

$url The URL to verify.

$absolute Whether the URL is absolute (beginning with a scheme such as "http:").

Return value

TRUE if the URL is in a valid format.

Related topics

Namesort iconDescription
Input validationFunctions to validate user input.

Code

<?php
function valid_url($url, $absolute = FALSE) {
  if ($absolute) {
    return (bool)preg_match("
      /^                                                # Start at the beginning of the text
      (?:ftp|https?):\/\/                               # Look for ftp, http, or https
      (?:                                               # Userinfo (optional)
        (?:[\w\.\-\+%!$&'\(\)*\+,;=]+:)*
        [\w\.\-\+%!$&'\(\)*\+,;=]+@
      )?
      (?:[a-z0-9\-\.%]+)                                # The domain
      (?::[0-9]+)?                                      # Server port number (optional)
      (?:[\/|\?][\w#!:\.\?\+=&%@!$'~*,;\/\(\)\[\]\-]*)? # The path (optional)
    $/xi", $url);
  }
  else {
    return (bool)preg_match("/^[\w#!:\.\?\+=&%@!$'~*,;\/\(\)\[\]\-]+$/i", $url);
  }
}
?>
 
 

All source code and documentation on this site is released under the terms of the GNU General Public License, version 2 and later. Drupal is a registered trademark of Dries Buytaert.