Archive for the ‘PHP & MySQL’ Category

PHP Domain Redirect

Sunday, June 17th, 2007

Our PHP Domain Redirect script is the perfect choice when you are parking domains at one central location and you need to split the web traffic to different addresses based upon the URL name. 

For example, say your primary location is firstdomain.com, but you also own a second domain name that is parked at this location (seconddomain.com). The key is to create different directories to store each website and then funnel the traffic based upon the domain name.

To accomplish this in PHP we employ a special PHP server variable called $_SERVER["HTTP_HOST"]. This variable contains the name of the URL as entered in the address bar of the web browser. You can find a list of all of the special PHP server variables on PHP.net. Some of the variables available are the document_root (contains the root location), http_referer (from what URL the vistor arrived at your site), http_user_agent (shows the browser and version of the vistor).

<?php 

$domain = $_SERVER["HTTP_HOST"];
if (($domain == "celtichearts.com") ||
   ($domain == "www.celtichearts.com")) { 

   header("location: http://www.celtichearts.com/mail"); 

} 

if (($domain == "webcelt.com") ||
   ($domain == "www.webcelt.com")) { 

   header("location: http://www.webcelt.com/news"); 

}
?>

Our script’s first job is to grab the URL from the address bar by using the server side variable $_SERVER["HTTP_HOST"]. We simply place that in the variable $domain and then test for each website – redirecting based on the name of the web address.

In this example, we show how The WEB CELT website uses PHP Domain Redirecting to host 2 different websites at one location. Because our hosting provider only allows 1 primary domain (www.celtichearts.com), we park the domain (www.webcelt.com) and then redirect both to the appropriate location.

Redirecting is accomplished by using PHP’s header() command. Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP – otherwise this will result in a nasty error.

And that is our quick and dirty PHP Domain Redirect Script. This is the perfect solution when you need a means to direct your vistors to different parts of your website based upon the URL the vistor entered. It is also a great way to accomplish redirects without learning or using .htaccess. Although I am sure we will be talking about .htaccess commands in future posts to The WEB CELT!