Monday, August 19, 2013

Make Subdomain a Variable with PHP

I wanted to create a dynamic page using a subdomain as a variable. What a user would do is put in a subdomain and it would pull up a page based off of that subdomain. For example: A user would type in http://car.file-drive.com and it would pull up a picture of a car. Of course car could be anything. It could be a list of names or anything at all. The way that it works is with a Wildcard subdomain. Here are the steps to do this.

1. Setup Wildcard Subdomain at your domain Registrar

You can skip this step if you host your dns record locally or with your hosting provider. I don't so I had to add the Wildcard record. My registrar is Godaddy so I just logged in, edited my DNS record and added a new CNAME record. I set the Host to * and it POINTS TO @

2. Setup Wildcard Subdomain with Web Host

My web host is Host Gator. I had to log in to the CPANEL and navigate to the subdomain settings. I added a new wildcard subdomain here for File-drive.com. So the settings again were * which is the character that means "any" just like a wild card in poker which can be any card. If this is an "add on" domain you'll need to point the subdomain to the proper root directory of your domain. File-drive is an add on so I had to point * to public_html/file-drive.com

3. Use PHP to Pull out the Variable

Now that the wildcard subdomain is set my domain can have any and as many subdomains as I want. What we have to do from this point is to break apart the url and get the variable from the subdomain. Will use
<?php $subdomain = array_shift(explode(".",$_SERVER['HTTP_HOST'])); ?>
to get the subdomain and set it to $subdomain.

At this point you can do all sorts of things. You could echo or print out the subdomain. You could make a database call using the subdomain variable. You could do pretty much anything you want to.
Enjoy!

No comments: