0

How to make sure that a string contains a valid/well formed url?

I need be sure the url in the string is well formed.

It must contain http:// or https://

and .com or .org or .net or any other valid extension

I tried some of the answers found here in SO but all are accepting "www.google.com" as valid.

In my case the valid url needs to be http://www.google.com or https://www.google.com.

The www. part is not an obligation, since some urls dont use it.

gnat
  • 6,213
  • 108
  • 53
  • 73
Lucas Matos
  • 1,112
  • 5
  • 25
  • 42

4 Answers4

3

Take a look at the answer here: PHP regex for url validation, filter_var is too permisive

filter_var() could be just fine for you, but if you need something more powerful, you'll have to use regex.

Additionally with the code from here, you can sub-in any regex that suits your needs:

<?php 
    $regex = "((https?|ftp)\:\/\/)?"; // SCHEME 
    $regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass 
    $regex .= "([a-z0-9-.]*)\.([a-z]{2,3})"; // Host or IP 
    $regex .= "(\:[0-9]{2,5})?"; // Port 
    $regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path 
    $regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query 
    $regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor 
?> 

Then, the correct way to check against the regex list as follows: 

<?php 
       if(preg_match("/^$regex$/", $url)) 
       { 
               return true; 
       } 
?>
Community
  • 1
  • 1
vladko
  • 1,013
  • 14
  • 21
1

YOU can do this by using php filter_var function

$valid=filter_var($url, FILTER_VALIDATE_URL)

if($valid){
//your code
}
StaticVariable
  • 5,253
  • 4
  • 23
  • 45
0

there's a curl solution:

function url_exists($url) {
    if (!$fp = curl_init($url)) return false;
    return true;
}

and there's a fopen solution (if you don't have

function url_exists($url) {
    $fp = @fopen('http://example.com', 'r'); // @suppresses all error messages
    if ($fp) {
        // connection was made to server at domain example.com
        fclose($fp);
        return true;
    }
    return false;
}
0

filter_var($url, FILTER_VALIDATE_URL) can be first used to make sure you are dealing with a valid URL.

Then you have more conditions that can be tested by assuming the URL is indeed valid with parse_url:

$res = parse_url($url);
return ($res['scheme'] == 'http' || $ret['scheme'] == 'https') && $res['host'] != 'localhost');
SirDarius
  • 41,440
  • 8
  • 86
  • 100