1

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
?>
BoltClock
  • 630,065
  • 150
  • 1,295
  • 1,284
Liutas
  • 4,743
  • 4
  • 19
  • 22

3 Answers3

7

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
  • 630,065
  • 150
  • 1,295
  • 1,284
  • 1
    You can also specify some options (path or query required): http://www.php.net/manual/en/filter.filters.validate.php – Andrea Zilio Jun 21 '10 at 13:59
  • 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 Jun 21 '10 at 14:04
  • Thanks this is what I searching for. – Liutas Jun 21 '10 at 14:05
3

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
  • 190,605
  • 114
  • 394
  • 474
  • 3
    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 Jun 21 '10 at 13:54
  • Beyond this the best way to validate an URL is to make a HTTP request and see if the response is valid. – Pentium10 Jun 21 '10 at 14:00
  • I cant do this because this can be sensitive url – Liutas Jun 21 '10 at 14:07
0

You can check if ParseUrl returns false.

Morfildur
  • 12,196
  • 6
  • 32
  • 54