views:

115

answers:

3

I need some function to check is the given value is a url.

I have code:

<?php
$string = get_from_db();
list($name, $url) = explode(": ", $string);
if (is_url($url)) {
    $link = array('name' => $name, 'link' => $url);
} else {
    $text = $string;
}
// Make some things
?>
+3  A: 

use parse_url and check for false

<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';

print_r(parse_url($url));

echo parse_url($url, PHP_URL_PATH);
?>

The above example will output:

Array
(
   [scheme] => http
   [host] => hostname
   [user] => username
   [pass] => password
   [path] => /path
   [query] => arg=value
   [fragment] => anchor
)
/path
Pentium10
but in manula it sai: "This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial URLs are also accepted, parse_url() tries its best to parse them correctly. "
Liutas
Beyond this the best way to validate an URL is to make a HTTP request and see if the response is valid.
Pentium10
I cant do this because this can be sensitive url
Liutas
A: 

You can check if ParseUrl returns false.

dbemerlin
+5  A: 

If you're running PHP 5 (and you should be!), just use filter_var():

function is_url($url)
{
    return filter_var($url, FILTER_VALIDATE_URL) !== false;
}

Addendum: as the PHP manual entry for parse_url() (and @Liutas in his comment) points out:

This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial URLs are also accepted, parse_url() tries its best to parse them correctly.

For example, parse_url() considers a query string as part of a URL. However, a query string is not entirely a URL. The following line of code:

var_dump(parse_url('foo=bar&baz=what'));

Outputs this:

array(1) {
  ["path"]=>
  string(16) "foo=bar&baz=what"
}
BoltClock
You can also specify some options (path or query required): http://www.php.net/manual/en/filter.filters.validate.php
Andrea Zilio
Definitely the best solution. My current project contains a really long regex to check for valid URLs, and tomorrow it's going to be replaced with this. Thanks!
nickf
Thanks this is what I searching for.
Liutas