To check if a string is a valid URL in PHP, you can use the filter_var
function with the FILTER_VALIDATE_URL
filter. This function returns true
if the string is a valid URL, or false
if it is not.
Here’s an example:
$url = 'https://www.example.com';
if (filter_var($url, FILTER_VALIDATE_URL)) {
// The URL is valid
} else {
// The URL is invalid
}
By default, the FILTER_VALIDATE_URL
filter only allows URLs with the HTTP and HTTPS protocols. If you want to allow other protocols, such as FTP or mailto, you can use the FILTER_FLAG_SCHEME_REQUIRED
and FILTER_FLAG_HOST_REQUIRED
flags:
$url = 'ftp://user:pass@example.com/path';
if (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED | FILTER_FLAG_HOST_REQUIRED)) {
// The URL is valid
} else {
// The URL is invalid
}
You can also use the parse_url
function to check if a string is a valid URL. This function returns an associative array with the various parts of the URL, or false
if the URL is invalid.
Here’s an example:
$url = 'https://www.example.com';
$parts = parse_url($url);
if ($parts !== false) {
// The URL is valid
} else {
// The URL is invalid
}
Note that the parse_url
function does not check the validity of the URL scheme or hostname, so it may not catch all invalid URLs. It is mainly useful for parsing and manipulating URLs, rather than for validation.