How to parse a URL in PHP to get the domain / host name

by Yang Yang on December 29, 2008

Share This Article:
Subscribe to Kavoir: blog feed

This is just that easy to do as picking up a dollar on the ground.

You can, of course write your own function to parse a string that looks like a URL and return various parts such as the domain, directory, requested file and possible data fields. However, PHP has come with exactly the function you need so you really don’t have to reinvent the wheel.

That is parse_url().

$url_parts = parse_url('http://www.google.com/search?q=obama');
print_r($url_parts);

The output looks like:

Array
(
[scheme] => http
[host] => www.google.com
[path] => /search
[query] => q=obama
)

The returned is an array containing a breakdown of the given URL. This way not only do you have the host name (www.google.com) but also protocol scheme (http), server path (/search) and query string (q=obama).

Easy enough, huh?

Share This Article:
Subscribe to Kavoir: blog feed

You should also read:

{ 1 comment… read it below or add one }

dolly July 14, 2010 at 1:36 am

hello all.,
Is there a way i can get the localhost of a website using php? please reply

Reply

Leave a Comment

Previous post:

Next post: