Basecamp Style Subdomains With CodeIgniter

Basecamp Style Subdomains With CodeIgniter

Tutorial Details
  • Topic: CodeIgniter
  • Language: PHP
  • Difficulty: Intermediate
  • Estimated Completion Time: An hour

CodeIgniter is a simple and lightweight PHP framework used to create powerful web applications. Today, we are going to do something nifty: we’ll combine user names and subdomains to make for a more cohesive user experience.

If you’re a bit confused, this feature allows your users to access their accounts by typing in a custom url, which maps to their user name, such as harbinger.yourapp.com.


Overview

In this tutorial, we are going to be creating both a front-end view and a back-end application view, similar to the configuration used in Basecamp, where visiting basecamphq.com shows the homepage, but visiting a subdomain displays the login page.

We will be using the fictional address nettutsapp.com, and will create a sample “dashboard” page; however, you could incorporate this into an existing project with relative ease.

basecamp-comapre

Before you begin, make sure that you have a web server with PHP installed. You also need to download CodeIgniter; in the example, I am using CodeIgniter 2.0, but the code should work on 1.7.2. So let’s get started!


Step 1: DNS Configuration

First, we need to configure our DNS settings to make all subdomains resolve to a single address. If you are working on a live server, then you will have to change your DNS settings with the company who handles your DNS. This is most commonly your web host or domain registrar.

To cover each configuration in this tutorial would take too much time. Instead, ask your host for some help to set up wildcard subdomains. You might expect to add something like the line below to your DNS configuration.

*.nettutsappapp.com.      IN  A    91.32.913.343

Instead, if you are working on a local server, adding a wildcard subdomain to the hosts file is quite tricky. What I prefer to do is add single entries for testing purposes. These can be deleted after you have finished. For our domain, we need to add four entries as follows:

  • 127.0.0.1     nettutsapp.com
  • 127.0.0.1     user1.nettutsapp.com
  • 127.0.0.1     user2.nettutsapp.com
  • 127.0.0.1     user3.nettutsapp.com

Mac Hosts Configuration

To do this on a Mac, open Terminal and type sudo nano /etc/hosts. Use the arrow keys to move to the bottom of the document, and add the entries to the bottom of the file. Once done, press Ctrl+X and Y to confirm the save.

dns-terminal1

Windows Hosts Configuration

If you are using Windows, browse to the directory C:\Program Files\system32\drivers\etc and open the hosts file in Notepad, or your preferred text editor. Add four entries, shown above, and save the file.

If you’ve made DNS changes to a live server, it will take a while before you notice any effect. If you made changes to your hosts file, the changes will be immediate.


Step 2: Apache Configuration

The aim here is to set up two Virtual Hosts in the Apache Configuration,:one serves the front end page (Basecamp Homepage), and the other serves the page seen when accessed via a subdomain (Dashboard Page).

To add new entries, you need to open the httpd.conf file, which can be found in the Apache installation directory. It’s often found in the bin/apache/conf folder. However, depending on your server configuration, the location may vary.

Once opened, you need to add the two entries, shown below. Be sure to change the DocumentRoot to a location of your choice, which you have created.

Note: Remember the wildcard and the different directory path on the second VirtualHost.

WAMP Users: I recommend reading this post, which describes how to set up VirtualHosts. You may also encounter permission problems; so I recommend placing your VirtualHost directories inside the www directory.

	<VirtualHost *:80>
		DocumentRoot "/Users/densepixel/Sites/MAMP PRO/nettutsappfront"
		ServerName nettutsapp.com
		ServerAlias nettutsapp.com
	
		<Directory "/Users/densepixel/Sites/MAMP PRO/nettutsappfront">
			Options -Indexes 
			Options FollowSymLinks
			AllowOverride All
		</Directory>
	</VirtualHost>
	
	<VirtualHost *:80>
		DocumentRoot "/Users/densepixel/Sites/MAMP PRO/nettutsapp"
		ServerName nettutsapp.com
		ServerAlias *.nettutsapp.com
	
		<Directory "/Users/densepixel/Sites/MAMP PRO/nettutsapp">
			Options -Indexes 
			Options FollowSymLinks
			AllowOverride All
		</Directory>
	</VirtualHost>
	

Once you have saved the file, you need to restart Apache for the changes to take effect.

Make sure that you have created the directories you specified in the httpd.conf file before starting the server.


Step 4: Testing Our Server Configuration

Before we test the configuration, place a basic html page in each of the directories you created earlier. Maybe add a single line of text to each, so you can differentiate them. I have copied an example for you to use.

<!DOCTYPE html>
<html lang="">
<head>  
	<meta charset="utf-8">
	<title>NetTuts App Front</title>
</head>
<body>
	NetTutsApp Front
</body>
</html>

Next, open your favorite browser, and first check the address nettutsapp.com. If everything works, you should be looking at the page you placed in the ‘nettutsappfront‘ directory.

Next, check a subdomain, eg. user1.nettutsapp.com; this should show you the other page you created in the directory.

config-success

You can go on to check the other subdomains you specified in the hosts file, which should all show the page saved within our directory.

Step 5: CodeIgniter Installation

This tutorial assumes that you know how to install CodeIgniter. If not, you should take a look at this video tutorial by Jeffrey Way, which explains the process in detail.

Place the CodeIgniter files into our directory after deleting the html page we created before. If you are using CodeIgniter 1.7.2, you may want to take the application folder out of the system folder.

nettutsapp-ci

Test the installation by browsing to the URL user1.nettutsapp.com, and you should see the CodeIgniter Welcome Page.

nettutsapp-ci-welcome

Step 6: Setting up CodeIgniter

Set up CodeIgniter as you normally would, as described in this tutorial. You may want to remove the index.php from the URL, autoload some libraries or helpers, etc. For the purposes of this tutorial, we need to autoload the database library and the url helper. Open the autoload.php file in the config directory, and add the relevant entries.

We also need to change the default controller to one which we will be making, called dashboard. This value can be changed within the /config/routes.php file.

Base_url

For the user subdomains, we need to make the base_url variable dynamic, as the application will be receiving requests from a number of potential subdomains.

The easiest way to do this is by using the HTTP_HOST variable. Open the config.php file, and find the variable $config['base_url'], and replace it with the following code:

if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on"){$ssl_set = "s";} else{$ssl_set = "";}
$config['base_url'] = 'http'.$ssl_set.'://'.$_SERVER['HTTP_HOST'];

This code allows for HTTPS connections, however, if you never plan on using HTTPS, you can simplify it to base_url = $_SERVER['HTTP_HOST'].

Database Settings

Before we go ahead and add the database settings into our CodeIgniter application, we need to create both the database and a sample table.

This example application uses one database and one table. This table will hold all the subdomains currently assigned, and some basic information about them. If you’ve decided to use this code in your own application, you’ll have to generally assign multiple users to a single subdomain, however that database schema is beyond the scope of this tutorial.

The table is named nt_subdomains, within the database ntapp, and has four fields:

  • subdomain_id(primary, auto_increment)
  • subdomain_name
  • user_fname
  • user_sname

I have also populated the table with two records, which match the subdomains we’ve added to our hosts file:

php-my-admin

Now we can open the database config, file found in /application/config/database.php, and edit the following values so that they match your personal configuration settings.

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root'; //MAMP default
$db['default']['password'] = 'root'; //MAMP default
$db['default']['database'] = 'ntapp';

And we’re done setting up our CodeIgniter installation. Let’s start using the subdomains in our application.


Step 7: Creating Our Controllers and Views

For this application, we are going to create two controllers. The first is an error controller, which displays an error if the subdomain has not been registered for use in the application. The other controller is our main dashboard controller, which is what the user sees if the subdomain has been added to our database.

Error Controller

Let’s go ahead and create our error controller. First, create a new file in the /application/controllers directory, and call it error.php.
Note: The name of the file is important

<?php

class Error extends Controller {

	function Error()
	{
		parent::Controller();
	}

	function index()
	{
		$this->load->view('error');
	}
}

Add the code above to our new error.php file. The index function loads a view called ‘error‘, which we will be creating later.

Dashboard Controller

Now we need to create the main dashboard controller, which will be loaded when a user enters one of the subdomains. The controller will then check whether the subdomain has been registered, and will redirect as necessary. We’ll add this code later, but first, we need to create the basic controller.

Create a new file within the controllers directory, and name it dashboard.php. Within this file, we need to create the controller and load the dashboard view. Copy the code below and save the file.

<?php

class Dashboard extends Controller {

	function Dashboard()
	{
		parent::Controller();
	}

	function index()
	{
		$this->load->view('dashboard');
	}
}

Error View

The error page will be displayed when a user tries to access a subdomain, which has not been registered for use by the application. For the purposes of the tutorial, simply create a basic page, displaying the message Subdomain Not Registered. Add the code below to a new file called error.php and save it within the application/views folder.

<html>
<head>
	<title>Application Error : Nettuts App</title>
</head>
<body>

	<h1>Nettuts Application Error</h1>

	<p>Subdomain Not Registered</p>

</body>
</html>

Dashboard View

initial-dashboard

For the time being, we will only be creating a basic dashboard page. You can use the same structure as the error view, and just change it to read Nettuts Dashboard, or something along those lines. Save the page as dashboard.php, within the application/views folder.

Test the two views by visiting the URLs:

  • user1.nettutsapp.com/index.php/error
  • user1.nettutsapp.com/index.php/dashboard

Working? Let’s move on.


Step 8: Extending Our Dashboard Controller (Part 1)

The next step is to extract the subdomain name in our controller so we can use it in a database query.

We are going to insert our subdomain checking code into the construct function within the dashboard controller. (Underneath the parent::Controller()). This means that the subdomain will be checked when any of the functions within the dashboard controller are accessed.

The easiest way to extract the subdomain name is to use the PHP explode function, and set the delimiter to ‘.’. As we only need the first part, we can split it into two parts, and then assign the first part (the subdomain name) to a variable.

To test this, we can echo the variable out in the controller itself. See the code below:

<?php

class Dashboard extends Controller {

	function Dashboard()
	{
		parent::Controller();
		
		$subdomain_arr = explode('.', $_SERVER['HTTP_HOST'], 2); //creates the various parts
		$subdomain_name = $subdomain_arr[0]; //assigns the first part
		echo $subdomain_name; // for testing only
	}
}

Access your subdomain URLs, and you should see the correct subdomain echoed on your page, as below.
Note: You can delete the echo statement now.

subdomain-parse1

Now that we have access to the subdomain name in our controller, we can check to see if it has been added the table we created earlier.

We will be using CodeIgniter’s ActiveRecord Class to build our queries, which will check the table for the accessed subdomain. If it is present, then the user will be able to access the dashboard page. If, on the other hand, the subdomain has not been entered, then they are denied access, and are then redirected to the error page we created earlier.

For this tutorial, we won’t be using models as it makes the tutorial much easier to follow. CodeIgniter is quite flexible in that it doesn’t force you to use them.

First, we need to assemble the query as show below. This code will only work in PHP5, as it uses method chaining; however, you can change it to your liking.

// adds on from rest of construct //
$this->db->from('nt_subdomains')->where('subdomain_name', $subdomain_name);
$query = $this->db->get();

We can use the CodeIgniter function row() to check whether that subdomain exists in the table. If it doesn’t, then we need to use the redirect function to redirect our users to the error controller. The next part of the code is below:

// adds on from previous code //
if($query->num_rows() < 1)
		{
		redirect ('error');
		}

Let’s test this by accessing user1.nettutsapp.com, which should direct you to the dashboard page. Now, try user3.nettutsapp.com, which should redirect you to the error page as it was not entered into the table.

subdomain-comapre1

Step 9: Extending Our Dashboard Controller (Part 2)

Now we can use the information in the table to display specific information for each subdomain.

We’ll add to the index function in our dashboard controller. First, copy the subdomain name code and the database query we used before.

function index()
	{
		$subdomain_arr = explode('.', $_SERVER['HTTP_HOST'], 2);
		$subdomain_name = $subdomain_arr[0];
		
		$this->db->from('nt_subdomains')->where('subdomain_name', $subdomain_name);
		$query = $this->db->get();
		
	}

We are using CodeIgniter’s row() function to retrieve the result of the query. The row function returns a single result row, which means we don’t need to use a foreach loop; it’s unnecessary.

// adds on from rest of index function //
$subdomain_info = $query->row();

Then, assign the user_fname and user_sname column values to the array, $data, which is then passed to the view.

$data['fname'] = $subdomain_info->user_fname;
$data['sname'] = $subdomain_info->user_sname;
$this->load->view('dashboard', $data);

We can use these values within our view by using the variables $fname and $sname. Open the dashboard view and edit it to read:

	<p>Welcome to your dashboard 
	<b><?php echo $fname; ?> <?php echo $sname ?></b>
	</p>

And we’re done! Let’s test it.


Step 10: Testing

Try all of the URLs, and hopefully, if everything went according to plan, the results should be as follows:

  • nettutsapp.com → Front End Page
  • user1.nettutsapp.com → Dashboard (John Doe)
  • user2.nettutsapp.com → Dashboard (Steve Smith)
  • user3.nettutsapp.com → Error Page
finalresult

Controller and View Code

Here’s the complete cote used for our controllers and views:

Dashboard Controller

<?php

class Dashboard extends Controller {

	function Dashboard()
	{
		parent::Controller();
		
		$subdomain_arr = explode('.', $_SERVER['HTTP_HOST'], 2);
		$subdomain_name = $subdomain_arr[0];
		
		
		$this->db->from('nt_subdomains')->where('subdomain_name', $subdomain_name);
		$query = $this->db->get();
		
		if($query->num_rows() < 1)
		{
		redirect ('error');
		}

	}

	function index()
	{
		$subdomain_arr = explode('.', $_SERVER['HTTP_HOST'], 2);
		$subdomain_name = $subdomain_arr[0];
		
		$this->db->from('nt_subdomains')->where('subdomain_name', $subdomain_name);
		$query = $this->db->get();
		
		$subdomain_info = $query->row();
		$data['fname'] = $subdomain_info->user_fname;
		$data['sname'] = $subdomain_info->user_sname;
		$this->load->view('dashboard', $data);
	}
}

Error Controller

<?php

class Error extends Controller {

	function Error()
	{
		parent::Controller();
	}

	function index()
	{
		$this->load->view('error');
	}
}

Dashboard View

<html>
<head>
	<title>Dashboard : Nettuts App</title>
</head>
<body>

	<h1>Nettuts Dashboard</h1>

	<p>Welcome to your dashboard 
	<b><?php echo $fname; ?> <?php echo $sname ?></b>
	</p>
	
</body>
</html>

Error View

<html>
<head>
	<title>Application Error : Nettuts App</title>
</head>
<body>

	<h1>Application Error</h1>

	<p>Subdomain Not Registered</p>

</body>
</html>

Conclusion

Of course, this tutorial describes only one way of obtaining this nifty functionality. I’m sure there are many more; so feel free to chime in with your thoughts and opinions in the comments section below.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Sandra Pertence

    nice tutorial, thanks.

  • Chintan

    AWESOME AWESOME tutorial, thanks mate :D

  • Adrian

    Awesome Tutorial, I’ve been looking for something like this for a long time now.

  • tillmannr

    Just what I was looking for. Thank you!

  • http://ran.yefet.net Ran

    Can we use CodeIgniter Also for the nettutsapp.com → Front End Page?

    • http://www.densepixel.com Atchyut Sekhar

      You could, the way this is done, the Front End is located in a different directory so you could have another Codeigniter installation.

    • http://dteam.us max

      Just point in the index.php of your front-end page app where CI system folder is located. You may use the same system folder for unlimited amount of apps.

  • Riley

    Why would you want to ping the database for a subdomain. Why not just store it in a custom config file?

    • http://codesanity.net Tom Schlick

      Because most likely you would want this running off your user db so when they create their account it is immediately available.

    • http://www.densepixel.com Atchyut Sekhar

      By config file, do you mean a static one, like the Codeigniter config file? In that case when you are making an app for users, you can’t add new users manually as they sign up. This method is quick and simple.
      You can also store information about the account; taking Basecamp as an example, when you pay for the account, you get a subdomain. You could store the plan and status in the database along with the subdomain name.

  • http://themeforest.net/item/space-creative-personal-blog-wordpress-theme/138592?ref=wizylabs WizyLabs

    AWESOME, you guys read my mind, I was looking for a similar tut since ages.

  • http://laroouse.com esranull

    bu kadar garip şeyleri nasıl öğreniyorsunuz gerçekten anlamış değilim

  • http://www.marioawad.com Mario Awad

    Excellent tutorial. Thanks.

    Please note that under Windows the hosts file is in here “C:\Windows\System32\drivers\etc”

    Also, depending on your configuration, you might need to run your text editor in administrator-mode to be able to modify it.

    Cheers.

    • http://www.ssiddharth.com Siddharth

      Updated. Thanks!

  • http://www.meditationsonlife.com John

    Very nice tutorial.

  • http://www.sidelanestudios.co.uk Ira Rainey

    A pretty good article, well done. I built something similar a few months back. Taking it a step further I also separated out the CI files into multiple applications. The logic being that if somebody visited the site at http://www.yourdomain.com then they would be taken to one app, but if they came via another subdomain it would take them to a different app. Essentially one for the normal front end site, and one for a back end application for clients.

    To do this I have the following directory structure:

    > public_html
    –> index.php
    > sys
    –> core
    —-> 1.7.2
    –> site
    –> client

    Where site and client are both CI separate application folders and the system is in \core\1.7.2

    To do this simply edit the start of the index.php file with the following:

    //
    // Determine the subdomain entered
    //
    $domain = $_SERVER['HTTP_HOST'];

    if(fnmatch(‘*.*.*’, $domain)) {
    $subdomain = explode(“.”, $_SERVER['HTTP_HOST']);
    $apploc = ($subdomain[0] == “www” && $subdomain[1] == “yourdomainname”) ? “sys/site” : “sys/client”;
    }
    else
    {
    $apploc = “sys/site”;
    }

    $subdir = “”;
    $sysloc = “sys/core/1.7.2″;
    $thispagehome = “public_html/”;

    //
    // System folder location
    //
    $path = realpath(dirname(__FILE__)).’/';
    $system_folder = substr($path, 0, ((strlen($path)-(strlen($thispagehome)))-(strlen($subdir)))).$sysloc;

    //
    // Application folder location
    //
    $application_folder = substr($path, 0, ((strlen($path)-(strlen($thispagehome)))-(strlen($subdir)))).$apploc;

  • Carlos

    Awesome!! Awesome!! Awesome!! Awesome!!

    Nettuts is THE source for high quality codeigniter tutorials.

    Thankyou!!

  • Erik

    The way the original author has done it, you’d have to get subdomain info in each of your controllers; a cleaner, DRY way to do this is to extend the controller class, and then build your controllers off that object. Phil Sturgeon has an excellent article on how to do so at http://philsturgeon.co.uk/news/2010/02/CodeIgniter-Base-Classes-Keeping-it-DRY

    • http://www.densepixel.com Atchyut Sekhar

      That is the way I have done it in my app as well. I just thought that it would be easier to show it this way and let advanced users play with it

  • Giedrius

    nice tutorial. Bravo.

  • http://www.emmyweb.com Dhruv

    This is really good,

    But how to do this without CI, i..e by just using php and apache, no frameworks.

  • http://willgretz.com Will Gretz

    you can also set up with a wildcard subdomain so you don’t have to edit your host file if you do not want too.

  • http://www.circuitbomb.com Dustin

    Very good tutorial Atchyut, thanks.

  • http://brianswebdesign.com Brian Temecula

    Maybe I’m wrong, but if base_url() yields an https:// version URL of HTTP_HOST when HTTPS == on, then how will you ever get out of the SSL environment? Any link that tries to exit the SSL environment but uses base_url() will have https://. For my own CI projects, I extend the URL helper with a secure_base_url() function. I’m not saying that’s the only way… but I don’t see it working your way.

    • http://www.densepixel.com Atchyut Sekhar

      In my app the user will always be in an SSL environment, if you really wanted you could set up your own variable without the https and use it whenever necessary

      • http://brianswebdesign.com Brian Temecula

        Thanks for the response. Just in case you or anyone wants to see what I was talking about, I’ve included my standard MY_url_helper:

        // USE_SSL is defined in a hook, along with a bunch of other stuff

        function secure_base_url()
        {
        $CI = get_instance();
        $url = $CI->config->slash_item(‘base_url’);
        if(USE_SSL === 1)
        {
        $url = substr($url, 0, 4).’s’.substr($url, 4);
        }
        return $url;
        }

        // I also have a function that checks if HTTPS == on //
        function if_secure_base_url()
        {
        $CI = get_instance();
        $url = $CI->config->slash_item(‘base_url’);
        if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == ‘on’)
        {
        $url = substr($url, 0, 4).’s’.substr($url, 4);
        }
        return $url;
        }

        // new current URL //
        function current_url()
        {
        $CI = get_instance();
        $url = $CI->config->site_url($CI->uri->uri_string());
        if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == ‘on’)
        {
        $url = substr($url, 0, 4).’s’.substr($url, 4);
        }
        return $url;
        }

  • Shaun C.

    This may seem like a dumb question, but is this any easier/better off than using a custom .htaccess file?

    I haven’t attempted to do anything like this with sub-domains, but I would imagine it should work all the same?

    • http://hosting4developers.com Hosting 4 Developers

      If you have a web app such as Basecamp with a number of users in a database, you’ll need to map the subdomain to one of the users in the database – that’s what CodeIgniter can do for you that .htaccess can’t.

      • Shaun C.

        Got it. Thank you for the response!

  • http://LeeNug.com Lee

    Awesome! I’ve been thinking about this recently! Nice One Nettuts! :)

  • http://hosting4developers.com Hosting 4 Developers

    Dashboard.php could have been written a lot simpler without sacrificing readability:

    - You’re repeating several lines of code from the constructor in index(). You could have just made a class property ($this->subdomain_name) so that you wouldn’t have to check HTTP_HOST and query the database twice.

    - Regarding this…
    $subdomain_arr = explode(‘.’, $_SERVER['HTTP_HOST'], 2);
    $subdomain_name = $subdomain_arr[0];
    If you know for a fact that the element you want (#0) is going to be there, you might as well just use list():
    list($subdomain_name) = explode(‘.’, $_SERVER['HTTP_HOST'], 2);

    - The query can be more easily written as
    $query = $this->db->get_where(‘subdomains’, array(‘subdomain_name’, $this->subdomain_name));

    # $subdomain_arr = explode(‘.’, $_SERVER['HTTP_HOST'], 2);
    # $subdomain_name = $subdomain_arr[0];
    #
    # $this->db->from(‘nt_subdomains’)->where(‘subdomain_name’, $subdomain_name);
    # $query = $this->db->get();

    • http://hosting4developers.com Hosting 4 Developers

      Please ignore the last five lines (the commented ones); they were copied into the input field by mistake.

    • http://www.densepixel.com Atchyut Sekhar

      Yes, should have done this and defined it in the constructor. Thanks for the suggestion.

  • Jose Perales

    If someone to start with MVC it is great way!!

  • http://www.ericsousa.com.br Eric Sousa

    I have a solution that uses just .htaccess.
    The subdomais goes as the first parametrer of the controller.

    RewriteCond %{HTTP_HOST} !^www\.urlsite\.com$ [NC]
    RewriteCond %{HTTP_HOST} ([^.]+)\.urlsite\.com$ [NC]
    RewriteRule ^(.*)$ http://www.urlsite.com/controler/index/%1/$1 [L]

  • http://www.alexnetwork.it Alex

    I add the ubuntu server way to add the vhosts:

    create 2 files in /etc/apache2/sites-available/ called nettutsapp.com and subdomain.nettutsapp.com, in the first add the:

    DocumentRoot “/Users/densepixel/Sites/MAMP PRO/nettutsappfront”
    ServerName nettutsapp.com
    ServerAlias nettutsapp.com

    Options -Indexes
    Options FollowSymLinks
    AllowOverride All

    and in the second:

    DocumentRoot “/Users/densepixel/Sites/MAMP PRO/nettutsapp”
    ServerName nettutsapp.com
    ServerAlias *.nettutsapp.com

    Options -Indexes
    Options FollowSymLinks
    AllowOverride All

    now to enable these vhosts run these commands:

    sudo a2ensite nettutsapp.com
    sudo a2ensite subdomain.nettutsapp.com
    sudo /etc/init.d/apache reload (dunno if it’s apache2 or apache at the moment, sorry for that)

    You have also to change path accordingly.

  • Sahan

    Awesome TUT!

  • http://www.oricosolutions.com Sean

    Great job, but as pointed out above, extending a base controller would have been best,
    and maybe a model? Not a bad start though I am creating a web app so will be using your tut!

  • http://beletsky.net alexanderb

    This is great tutorial!

    Are you plan to make same but for Windows/ASP.net MVC/IIS.. this would be just great :)

    Thanks!

  • Paul

    The query you have in the constructor should really set some information for the object so it doesnt have to run the query again.

    $this->subdomain = $query->row();

    Then in the index method, or whatever other method you wish to call you can simply refer to it with $this->subdomain->field

  • DoubleXero

    Great tut. I’m having alot of trouble getting mcrypt working on my Mac.
    Does anyone have good tut to follow for this?

  • http://mustafanamoglu.com/ Mustafa Namoğlu

    Thanks a lot, i’ve been looking for something like this.

  • http://websco.com.mx dejitaru

    The code you are posting is not for Codeigniter 2.0 .. its for 1.7.2
    In CI 2.0:

    class Error extends Controller {
    function Error()
    {
    parent::Controller();
    }
    ……….

    should be:

    class Error extends CI_Controller{
    public function __construct()
    {
    parent::__construct();
    }
    ……..

  • Beeksi Waais

    Nice Tut,

    I recently worked on this feature. I advise you to use the sessions to avoid having to check each time the subdomain.

    Such functionality requires a user login. It is unnecessary to check the subdomain if a user is already logged. Thus you avoid many unnecessary SQL query.

    • http://www.densepixel.com Atchyut Sekhar

      The example is very basic, in reality you would also check if the subscription is active gather account details etc.. These could change at any time and putting them in sessions wouldn’t work.
      You could cache the results for a few minutes if you wanted, but I think that querying wins over sessions. You would want to validate the session anyway, which would require a database query.

  • http://codefight.org/ Codefight CMS

    Awesome! Nice!! Great!!! … What else can i say. Simply awsomeee… Thanks for the tut.

  • abada

    nice tuts ….. thanks

    but the question is how configure DNS settings to make all subdomains

    automatically (by code) !!!1
    not manually method ?????

    plz help….

    thanks

  • http://tablen.com Moprit Tran

    Nice Tut,
    At currently, I’m working on multi-subdomain with CI, too. And I noticed a missing part in your article, which is the session and cookies configuration. Because if not, browser will treat the sub1.domain.com sub2.domain.com are different.
    As the author’s comment above, we can use DB to store the user’s session, and cookie should be configured as follows:

    $config['cookie_prefix'] = “MY_”;
    $config['cookie_domain'] = “.urldomain.com”; // Across multi-subdomain
    $config['cookie_path'] = “/”;

    Anyway this is great tutorial.

  • AC

    Has anyone been able to pull this off with domains in Godaddy ? or any other shared hosting?

    Great tutorial, many thanks.

  • abada

    please any ideas ??????

  • wizylabs

    Need help guys, the app dir redirects to the front dir!

  • wizylabs

    Can anyone please confirm that he/she got this working using WAMP or XAMPP on windows?

  • http://www.mnemonicdictionary.com Amit Aggarwal

    I have a small query :

    Based on calling subdomain, subdomain table in database is returning an extension corresponding to that subdomain…

    so say for stackoverflow.mywebsite.com it will return extension “sf”… and image folder and css file used all over the website will change on the basis of this extension.

    example : images_sf, style_sf.css

    Now, wht is the best way to fetch this extension anywhere in M , V or C ?

    Options :

    1) Cookies

    2) Dynamically set CI config variable

    3) set a variable for this in MY_Controller and access that variable via $this-> anwhere.

    4) send that variable from each controller to models, helpers, views or libraries. …

    Did I miss any other option ? Also, which one will be best assuming this will be heavily used all over the code …

    Thanks,
    Amit

  • Hutch

    Is there a way to accomplish this with one codeigniter install without changing the apache config?

  • Mark

    I have a question. If I am taking this to a live server – I know we set up the wildcard – but what about virtual hosts? is this a requirement or what process would be required for the dynamic side of things for the server.

    Thanks

  • Mark Fasel

    What do we do if everything is stored in one install – ie the front end and user controllers are all stored in one directory under one codeigniter install? Also with a live server – ie hostgator, if we don’t have access to modifying apache, is there a work around?

  • http://kerajinannusantara.com Yhu

    thanks :) great article

  • Mohammad Hussain

    I have the same query as Mark. Furthermore, I want to know about configuration through Putty.

  • Chris

    If this works it should be a PREMIUM Tutorial!!!

    I spent many many + many hours on this.

    Note: I had it working perfectly on local server,

    But, a Caution to you all, WHM and Apache have a lot of automation with configs, it is A LOT Different to your local environment.
    (don’t tell your boss about this great new feature until you see it working on the remote/live server ;o)

    I really do hope this works, it’s a very cool feature that I’m sure lots of coders will get great recognition for ;-)

    Thanks you for this.

  • Richard

    This is great to make a test enviroment.

  • http://www.cynergywebgroup.com/ Brandon

    Thanks for the very detailed tutorial. This helped me accomplish my project must faster!

  • http://www.cynergywebgroup.com/ Brandon

    Thanks for the tutorial, this was really a big help!

  • Wallysson Nunes

    Hello To everyone, at first, AWESOME POST. Like always, net tuts plus, for me are the best place to learn and get updated about web.

    Well guys, i reade all of this post and i tryed to make na thing to work.
    supposedly, we just can use wildcards at an live webserver, we cant do it locally because Windows (at my case) didn’t support it. I found an program that make possible the uses of wildcards, i tested it and it WORKED.

    The basic idea of it its change the default DNS porvider from windows. Here goes the link:
    http://mayakron.altervista.org/support/browse.php?path=Acrylic

    He had an easy installation and configuration! i just have a little problem configurationg the ports…
    (if someone wold like to try it and have problems too, just change the port number of 53 to 5353, it worked for me).

    Well, maybe you ask yourself: Why i would like to install it?
    To make sure you will be Reproducing the web environment, and its really nice you dont have to change the hosts file everytime.

    Well, thats it, hope that i could help someone!