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, then:

PROTOCOL = http://
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:

    [scheme] => http
    [host] =>
    [path] => /page

    No “sub” or “” which is what I was after when I wrote that. If your site uses addresses like 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 *