Lisa
Lisa

Reputation: 2139

parse_url defaults to path rather than host

Why does parse_url place domain information in path by default, rather than in host?

for example:

$url = 'www.example.com';
$parsed_url = parse_url($url);

If I do a var_dump on $parsed_url I get this:

array (size=1)
    'path' => string 'www.example.com' (length=15)

By default, shouldn't that be in host? If I prepend http:// to the value in $url, it distributes the information as expected.

Upvotes: 2

Views: 361

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

By definition a URL must contain a protocol/scheme like http://.

Partial URLs are also accepted, parse_url() tries its best to parse them correctly.

Try this to check for http:// and if not add it:

$url = strpos($url, 'http://') !== 0 ? "http://$url" : $url;

You might have to check for https:// as well so either do two checks or a regex would work:

$url = preg_match('#^https?://#') ? $url : "http://$url";

Upvotes: 4

Related Questions