PASSWORD RESET

Your destination for complete Tech news

PHP

How to check if a string is valid URL in PHP?

536 0
< 1 min read

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:[email protected]/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.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.