Check if a string contains nothing but an URL in PHP

50,472

Solution 1

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.

Solution 2

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';

Solution 3

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
    } 
    
Share:
50,472
yotka
Author by

yotka

Picture: http://www.zozoville.com/

Updated on July 09, 2022

Comments

  • yotka
    yotka almost 2 years

    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?