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 ?> 
3

3 Answers 3

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" } 
Sign up to request clarification or add additional context in comments.

3 Comments

You can also specify some options (path or query required): php.net/manual/en/filter.filters.validate.php
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!
Thanks this is what I searching for.
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 

3 Comments

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. "
Beyond this the best way to validate an URL is to make a HTTP request and see if the response is valid.
I cant do this because this can be sensitive url
0

You can check if ParseUrl returns false.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.