Waqas Khan
Waqas Khan

Reputation: 65

CodeIgniter with multiple subdomains

I have a problem and hopefully we will solve it.

The problem is, I am creating an application this application has an “Admin Panel (Backend)” and Frontend.

The URL structure of the admin panel is like this

https://www.app-name.com/admin

For frontend I have a different URL structure which is based on country for example.

https://usa.app-name.com

https://ca.app-name.com

https://uk.app-name.com

https://uae.app-name.com

https://in.app-name.com

It means in frontend I have multiple sub-domains. And the all these sub-domains are sharing a single database. As well as, backend is also sharing the same database.

Now my problem is how can I handle front-end like this.

Possible one solution in my mind is to copy app to all the sub-domains and connect with single database. And for admin panel copy it at the main domain.

But in this case, if I have a single modification to application I have to update all the copies. I want to use only single copy of app to handle all sub-domains.

Anyone have some solution for this problem. Thanks

Upvotes: 0

Views: 1604

Answers (1)

David
David

Reputation: 16726

I'd suggest executing some code in a important model for the app that gets auto-loaded through the entire app. Maybe call it Site_model.php.

Firstly, lets autoload the model. Open up config/autoload.php and add the model into the list of models to be autoloaded:

$autoload['model'] = array('Site_model');

Now, create the new model calls Site_model. In the construct of the model, add some code along these lines (this is a simply basic example of how to fetch and assign the value of a subdomain. I imagine there are better ways, but for this example, it will do):

class Site_model extends CI_Model {
   var $subDomain = '';
   function __construct() {
      $this->subDomain = array_shift((explode('.', $_SERVER['HTTP_HOST'])));

      // further code which uses the value of subDomain to fetch the correct record from the database.
   }

Now, anytime you want to reference the subdomain in your code, you can simply get it like this:

echo $this->Site_model->subDomain;

This should also work for the admin backend. Oh, and ensure that the model is the first to be auto-loaded, in case any of the other models that are auto-loaded initialise code that is dependent on the site model's values.

Upvotes: 1

Related Questions