Program & Design Tips, tricks, tutorials, and tools on programming & web design

23Jun/092

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

Filed under: PHP Leave a comment
Comments (2) Trackbacks (0)
  1. It can also be done using parse_url(). :)

  2. 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 comment


No trackbacks yet.