Check if a string contains nothing but an URL in PHP

PhpUrlValidation

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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 - Php

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 - Php

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
    } 
    

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionyanView Question on Stackoverflow
Solution 1 - PhpJohn CondeView Answer on Stackoverflow
Solution 2 - PhpWinstonView Answer on Stackoverflow
Solution 3 - PhpApps-n-Add-OnsView Answer on Stackoverflow