0

I have a website say example.com with 5 sub-domains: site1.example.com, site2.example.com, site3.example.com, site4.example.com, and site5.example.com.

When users visit example.com, they are presented with the other 5 sub-domains to choose from. I want to implement something that redirect the users to the sub-domain they choose the first time they visit the main domain. I know I can use cookies for this, but how can I implement this in Drupal?

1 Answer 1

2

This implementation of hook_init() should be present on your subdomains but not on your main domain:

function YOUR_MODULE_NAME_init() {
  if(!isset($_COOKIE['your_cookie_name'])) {
    /*Your need to set cookie for your main domain, as well as for all your subdomains otherwise once a user visits another subdomain by typing the url directly in the address bar the cookie would be overwritten*/
    setcookie('your_cookie_name', base64_encode($_SERVER['HTTP_HOST']), YOUR_EXPIRATION_TIME, '/', 'example.com');
    setcookie('your_cookie_name', base64_encode($_SERVER['HTTP_HOST']), YOUR_EXPIRATION_TIME, '/', 'site1.example.com');
    setcookie('your_cookie_name', base64_encode($_SERVER['HTTP_HOST']), YOUR_EXPIRATION_TIME, '/', 'site2.example.com');
    ...
    setcookie('your_cookie_name', base64_encode($_SERVER['HTTP_HOST']), YOUR_EXPIRATION_TIME, '/', 'site5.example.com');
  }
  else {
    header('Location: ' . base64_decode($_COOKIE['your_cookie_name']));
  }
}

Your main domain should have a module with the following code:

function YOUR_MODULE_NAME_init() {
  if(isset($_COOKIE['your_cookie_name'])) {
    header('Location: ' . base64_decode($_COOKIE['your_cookie_name']));
  }
}

I didn't test this code, but I am positive it should work, or at the very least it illustrates the approach.

6
  • Alex,thanks for giving me the idea/approach.I will try this and get back ASAP.
    – Jnr Fred
    Mar 8, 2012 at 15:54
  • I just added a small portion of code to my answer. Forgot to include the code for main domain :) Mar 8, 2012 at 15:57
  • i tried the above code but it seems not to be redirecting properly. For-instance i get this example.com/site1.example.com on my next visit. Am I doing something wrong?
    – Jnr Fred
    Mar 9, 2012 at 16:42
  • in the first code snippet replace: base64_encode($_SERVER['HTTP_HOST']) with base64_encode("http://" . $_SERVER['HTTP_HOST']). I think this should work then. Mar 10, 2012 at 22:29
  • I replaced the code as you said but i get this info in my browser "This webpage has a redirect loop".it fails to redirect to the previous visited link.Hmmm,any other suggestion.
    – Jnr Fred
    Mar 12, 2012 at 12:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.