2

Why is parse_url() returning empty string in this case?

$url = "www.example.com";
$host = parse_url($url, PHP_URL_HOST);
print_r($host);
1
  • 3
    Try adding http at the front of the URL? Commented Feb 29, 2012 at 14:53

3 Answers 3

3

The string is interpreted as relative URL:

// print_r(parse_url('www.vtechpcsupport.com'))
Array
(
    [path] => www.vtechpcsupport.com
)  
Sign up to request clarification or add additional context in comments.

4 Comments

Yep, but the weird thing is that parse_url documentation states: "This function doesn't work with relative URLs." Looks like this isn't "seriously malformed URL" ;)
It also says "Partial URLs are also accepted, parse_url() tries its best to parse them correctly."
@Juicy: Mmh. Maybe it is smarter than it claims. If I try www.vtechpcsupport.com?foo=bar it correctly identifiers foo=bar as query string.
@FelixKling, the documentation is a bit controversing, it claims "parsing URLs and not URIs" (with some "modifications") and have link to RFC 3986 which is "URI Generic Syntax"
2

This is due to fact that www.vtechpcsupport.com isn't really a URL since it missing the scheme part (HTTP or so), try it like this:

$url = 'http://www.vtechpcsupport.com';
$var = parse_url($url,PHP_URL_HOST);
print($var);

3 Comments

It’s a URL but not one with a host.
@Gumbo, it't really not ;) General URL Syntax
@Gumbo: just because browsers default to http for bare hostnames doesn't make it a url - a scheme is required for a proper url. e.g. what if that was actually 'ftp.vtechpcsupport.com' and didn't have a web server running on it?
1

This is because www.vtechpcsupport.com is not a complete URL.

You are specifying PHP_URL_HOST so the function tries to extract just the host part of the URL, which doesn't exist as without a protocol being given the URL is treated as being relative -- so what you want to be the host name is interpreted as a (relative) path.

Try using:

$url='http://www.vtechpcsupport.com';

and you should get the behaviour you expect.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.