How to validate a URL
Short answer
filter_var() with the FILTER_VALIDATE_URL filter checks the form of an address:
<?php
var_dump(filter_var('https://example.com/path?q=1', FILTER_VALIDATE_URL) !== false);
var_dump(filter_var('example.com', FILTER_VALIDATE_URL) !== false);Output:
bool(true)
bool(false)http and https only
The filter also accepts javascript: and ftp:. If the link is going to be shown on a page, check the scheme:
<?php
function isWebUrl(string $url): bool
{
return filter_var($url, FILTER_VALIDATE_URL) !== false
&& in_array(parse_url($url, PHP_URL_SCHEME), ['http', 'https'], true);
}
var_dump(isWebUrl('https://example.com'));
var_dump(isWebUrl('javascript://example.com/%0Aalert(1)'));Output:
bool(true)
bool(false)Functions used in this recipe
- filter_var — Validates or sanitises a value by a given rule.
- parse_url — Splits a URL into its parts.
- in_array — Checks whether a value exists in an array.