Ryan Ryan - 5 months ago 8
PHP Question

Best way to check if a URL is valid

I want to use PHP to check, if string stored in

$myoutput
variable contains a valid link syntax or is it just a normal text. The function or solution, that I'm looking for, should recognize all links formats including the ones with GET parameters.

A solution, suggested on many sites, to actually query string (using CURL or
file_get_contents()
function) is not possible in my case and I would like to avoid it.

I thought about regular expressions or another solution.

Answer

Use the native Filter Validator

filter_var($url, FILTER_VALIDATE_URL);

Example:

if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) {
    die('Not a valid URL');
}

See this tutorial about filter_var usage

Comments