How to validate URL in PHP

Snippet

1) The easiest way to check whether an email address is well-formed is to use the filter_var() function:

downloadcopy
<?php
$url = 'https://wtools.io';
$validation = filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED);
if ( $validation ) $output = "$url is a valid URL";
else $output = "$url is not a valid URL";
echo $output;

The FILTER_VALIDATE_URL filter validates a URL.
Possible flags:

  • FILTER_FLAG_SCHEME_REQUIRED - URL must be RFC compliant (like https://wtools)
  • FILTER_FLAG_HOST_REQUIRED - URL must include host name (like https://wtools.io)
  • FILTER_FLAG_PATH_REQUIRED - URL must have a path after the domain name (like wtools.io/php-snippets/)
  • FILTER_FLAG_QUERY_REQUIRED - URL must have a query string (like wtools.io?name=Peter&age=37)

2) If you want to know if the url really exists (via CURL):

downloadcopy
function urlExist($url){//se passar a URL existe
    $c=curl_init();
    curl_setopt($c,CURLOPT_URL,$url);
    curl_setopt($c,CURLOPT_HEADER,1);//get the header
    curl_setopt($c,CURLOPT_NOBODY,1);//and *only* get the header
    curl_setopt($c,CURLOPT_RETURNTRANSFER,1);//get the response as a string from curl_exec(), rather than echoing it
    curl_setopt($c,CURLOPT_FRESH_CONNECT,1);//don't use a cached version of the url
    if(!curl_exec($c)){
        return false;
    }else{
        return true;
    }
}

$url = 'https://wtools.io';
if ( urlExist($url) ) $output = "$url is a valid URL";
else $output = "$url is not a valid URL";
echo $output;

3) Validate via regex with http or https:

downloadcopy
<?php
$url = 'https://wtools.io';
$pattern = '/^(http|https):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(?::\d{1,5})?(?:$|[?\/#])/i';
if (preg_match($pattern, $url)) {
    $output = "$url is a valid URL";
} else {
    $output = "$url is not a valid URL";
}
echo $output;