Is regex a good way to validate a url

I am trying to verify the URL entered with php5 is correct. I thought about using regular expressions, but believing that it works correctly all the time, it solves the problem syntactically correct. This does not tell me anything about the correctness or operation of the URL.

I am trying to find another solution to do both, if possible. Or is it better to find 2 separate solutions for this?

If regex is the way to go, then what test regular expressions exist for URLs?

+5
source share
8 answers

Instead of hacking over the regex (the URLs are very complex), I just use filter_var()and then try ping the URL using cURL :

if (filter_var($url, FILTER_VALIDATE_URL) !== false)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_exec($ch);
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($status_code >= 200 && $status_code < 400)
    {
        echo 'URL is valid!';
    }
}
+11
source

To check out http://www.php.net/manual/en/filter.filters.validate.php

To check if it exists ... well, you should try to actually access it.

+3
source

, URL- " ", (, , -).

HTTP- Perl, LWP:: Simple, .

+2

:

  • , URL- filer_var FILTER_VALIDATE_URL.
  • file_get_contents URL- , $http_response_header[0] 200 HTTP.

, , , , .

+1
+1

regex , . ... → http://gskinner.com/RegExr/

+1

URL-, , URL-, !

  • , ?
  • What if the domain does not work with ping?

If you really want to do live testing, try resolving the URL using the DSN . DNS is more reliable than PING or HTTP.

<?php
$ip = gethostbyname('www.example.com');

echo $ip;
?>

But even if this invalid URL may be valid. It just does not have a DNS record. . It depends on your needs.

+1
source

All Articles