Extract domain, path etc from a full url with PHP
Posted September 28th, 2009 in PHP (Updated August 16th, 2010)
PHP's parse_url function makes it easy to extract the domain, path and other useful bits of information from a full URL. This can be useful for a variety of purposes, such as when spidering content from a website and needing to extract particular pieces of information from the links in the page.
Returning an associative array
The parse_url function takes the url as the first argument and an optional component value as the second argument. If the second argument is omitted then it returns the found values as an associative array.
This post is at http://www.electrictoolbox.com/php-extract-domain-from-full-url/ and getting the associative array of information from it is done like this:
$url = "http://www.electrictoolbox.com/php-extract-domain-from-full-url/"; $parts = parse_url($url);
Then doing print_r($parts) will output this:
Array
(
[scheme] => http
[host] => www.electrictoolbox.com
[path] => /php-extract-domain-from-full-url/
)
If they are present, the array will also contain values for port, user, pass (i.e. password), query (the query string component of the URL) and fragment (the part after the #).
Returning a string
If all you are after is a single component from the array as a single string, pass the second "component" parameter from the following constants: PHP_URL_SCHEME, PHP_URL_HOST, PHP_URL_PORT, PHP_URL_USER, PHP_URL_PASS, PHP_URL_PATH, PHP_URL_QUERY or PHP_URL_FRAGMENT.
To just get the domain from this blog post's URL, do this:
$url = "http://www.electrictoolbox.com/php-extract-domain-from-full-url/"; $domain = parse_url($url, PHP_URL_HOST);
PHP Documentation
For more information read the PHP manual page for this function.
Follow up posts
Have a read of my post titled "PHP: get keywords from search engine referer url" to find out how to use the parse_url function in conjunction with the parse_str function to see what query string visitors have entered into a search engine.
Related posts:
- PHP: get keywords from search engine referer url - version 2 (Friday, November 26th 2010)
- Get the headers sent from the browser with PHP (Thursday, September 17th 2009)
- Extract images from a web page with PHP and the Simple HTML DOM Parser (Monday, September 14th 2009)
- Get meta tags from an HTML file with PHP (Thursday, September 10th 2009)

Comments
blog comments powered by Disqus