53

I am wondering if this is a proper way to check, if a string contains nothing but an URL:

if (stripos($string, 'http') == 0 && !preg_match('/\s/',$string)) {
  do_something();
}

stripos() checks if the string starts with "http"
preg_match() checks if the string contains spaces

If not so, I assume that the string is nothing but an URL - but is that assumption valid? Are there better ways to achieve this?

John Conde
  • 217,595
  • 99
  • 455
  • 496
yotka
  • 1,002
  • 2
  • 11
  • 19
  • 2
    possible duplicate of [the best way to check if a url is valid?](http://stackoverflow.com/questions/2058578/the-best-way-to-check-if-a-url-is-valid) – trejder Jul 30 '15 at 09:46

3 Answers3

161

Use filter_var()

if (filter_var($string, FILTER_VALIDATE_URL)) { 
  // you're good
}

The filters can be even more refined. See the manual for more on this.

Limon Monte
  • 52,539
  • 45
  • 182
  • 213
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • Thanks a lot! (I think both answers came at the same time) – yotka Feb 22 '13 at 17:14
  • Thanks, this is better than parse_url($string), because anything with a colon (:) would get dinged as a url. Works alot better. Wish there was a way to detect if it was a url even if it did not have the http:// though. – alexander7567 Aug 06 '13 at 19:02
  • 1
    This failed to successfully validate a URL where I had the chracter `å` in it - but the URL was working. (Using PHP 7.0) – TheStoryCoder Aug 24 '17 at 02:44
  • 1
    This FAILED to validate valid URLs where they contain % chracters – Kyle KIM Apr 24 '18 at 14:38
10

In PHP there is a better way to validate the URL:

http://www.php.net/manual/en/function.filter-var.php

if(filter_var('http://example.com', FILTER_VALIDATE_URL)) {
    echo 'this is URL';
}
ScreamX
  • 339
  • 1
  • 3
  • 13
Winston
  • 1,758
  • 2
  • 17
  • 29
1

To more securely validate URLs (and those 'non-ascii' ones), you can

  1. Check with the filter (be sure to check the manual on which filter suits your situation)

  2. Check to see if there are DNS records

    $string = idn_to_ascii($URL);
    if(filter_var($string, FILTER_VALIDATE_URL) && checkdnsrr($string, "A")){
        // you have a valid URL
    } 
    
JON
  • 965
  • 2
  • 10
  • 28
Apps-n-Add-Ons
  • 2,026
  • 1
  • 17
  • 28