Get Domain & Subdomain from URL

preg_match('/^(?:www\.)?(?:(.+)\.)?(.+\..+)$/i', $_SERVER['HTTP_HOST'], $matches);

define('PROTOCOL', strtolower(substr($_SERVER['SERVER_PROTOCOL'],0,strpos($_SERVER['SERVER_PROTOCOL'],'/'))).'://');
define('SUBDOMAIN', $matches[1]);
define('DOMAIN', $matches[2]);
define('HERE', $_SERVER['REQUEST_URI']);

If you’re at http://www.sub.domain.com/page, then:

PROTOCOL = http://
SUBDOMAIN = sub
DOMAIN = domain.com
HERE = /page

Posted in

2 thoughts on “Get Domain & Subdomain from URL

  1. OMG, a legitamate comment! I didn’t know about parse_url, but with the above address, it gives:

    Array
    (
    [scheme] => http
    [host] => http://www.sub.domain.com
    [path] => /page
    )

    No “sub” or “domain.com” which is what I was after when I wrote that. If your site uses addresses like username.domain.com or something, this can be helpful to have.

    Thanks for the tip though :)

Leave a Reply

Your email address will not be published. Required fields are marked *