00 Votes

PHP: Is String a valid URL?

Question by Guest | 2015-06-17 at 09:41

Is there any possibility in PHP to check a string (for example a user input) in order to verify that this string is a valid URL (address of a website)?

ReplyPositiveNegative
0Best Answer0 Votes

Yes, you can just use the function filter_var() to validate a URL. Let us look at a small example:

$url = "https://www.askingbox.com";

if (filter_var($url, FILTER_VALIDATE_URL)) {
    echo("$url is a valid URL");
} else {
    echo("$url is not a valid URL");
}

First, you have to pass your string to the function and as a second parameter, you have to pass the constant FILTER_VALIDATE_URL to ensure that the function is checking for a URL.

Optionally, you can also use one of the following flags as a third parameter.

  • FILTER_FLAG_PATH_REQUIRED: Requires the URL to contain a path part, for example www.example.com/example/
  • FILTER_FLAG_QUERY_REQUIRED: Requires the URL to contain a query string, for example "example.com?id=100&action=2"
  • FILTER_FLAG_SCHEME_REQUIRED: URL must be RFC compliant, for example http://example (by default)
  • FILTER_FLAG_HOST_REQUIRED: URL must include host name, for example http://www.example.com (by default)

In order to check whether a URL is containing a path, for example you can call "if (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED))".

The flags FILTER_FLAG_SCHEME_REQUIRED and FILTER_FLAG_HOST_REQUIRED are activated by default so that you do not have to specify them.
2015-06-17 at 18:30

ReplyPositive Negative
Reply

Related Topics

HTACCESS: Simplify URL

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.