-1

Is there a way to find if ad url is valid

I tried this code

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

but if I try with http://www.gsrgrs.grsgsrg, for example, the result is ok.

Edit: The goal is to see if there's a live website there.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
P_R
  • 356
  • 2
  • 7
  • 27

1 Answers1

2

http://www.gsrgrs.grsgsrg is a perfectly valid URL, therefore the test result is correct.

If your intent is to discover whether a URL points to a valid resource instead, you should employ cURL or a similar library to attempt a fetch operation, and test for the protocol response code, for example with:

$http = curl_init($url);
$result = curl_exec($http);
$http_status = curl_getinfo($http, CURLINFO_HTTP_CODE);
curl_close($http);
if($http_status == 200)
    echo 'Ooooh, we got a 200 OK response from the webserver!';
else
    echo 'Meh, failed with '.$http_status.' :(';
Niels Keurentjes
  • 41,402
  • 9
  • 98
  • 136
  • Sorry, for valid URL I suppose valid in the sense that there's a live website there – P_R Jun 26 '14 at 13:49
  • Why bother? Anyway you'd probably have to use spiders to crawl the sites and see if they hit anything. – Jonast92 Jun 26 '14 at 13:58