Scriptplayground

 Print Page | Close Window

Grab Subdomain From Url

Use this block of code to grab the subdomain from the URL. You can then use it in any part of your code.

This requires your host to have: #ServerAlias *.domain.com in the .htaccess file of in the config of Apache otherwise Apache just redirects to a domain name.

<?php

// Whether or not to output debug code
//DEFINE("DEBUG", 1);
DEFINE("DEBUG", 0);

// An array of actual subdomains on the server
$real_subdomains = array('subdomain1','subdomain2');

// The domain info for this site
$domain_name = 'domain';
$domain_tld = '.com';

// Set a variable to hold the host info
$host_info = '';

// Check to see if 'register_globals' is on
if(ini_set('register_globals' == 1))
	{
	$host_info = $HTTP_HOST;
	}
else
	{
	$host_info = $_SERVER['HTTP_HOST'];
	}

// Break up the pieces of the host info
$parts = explode(".", $host_info);

// Pull the 'subdomain' for the url
$subdomain = $parts[0];

(DEBUG) ? print "Host Info: " . $host_info : '';

// Check that the subdomain isn't 'www' or the domain name
if(($subdomain != "www") && ($subdomain != $domain_name))
	{
	// Is the subdomain a real domain?
	if(in_array($subdomain, $real_subdomains))
	{
	// Redirect and exit
	header("Location: http://www." . $domain_name . $domain_tld . "/" . $subdomain . "/");
	exit();
	}
	else
	{
	header("Location: http://www." . $domain_name . $domain_tld . "/");
	}
	}

?>

The above code has been commented for easy use. This will work if "register_globals" is on or off.


Find this article at:
http://scriptplayground.com/tutorials/php/Grab-Subdomain-From-Url/