Php set subdomain cookies and redirect

I have the cookies and subdomain selection for header:

<script type="text/javascript" src="/static/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(function(){
var city = readCookie('city');
if(city !=null && city !=''){
window.location.href = 'http://' + city + '.example.com';
}
$('#citygo').change(function(){
var city = $(this).val();
window.location.href = 'http://' + city + '.example.com';
});
});
function createCookie(name,value,days) {
if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
</script>
<select id="citygo">
<option value="0">Select City</option>
<option value="amsterdam">Amsterdam</option>
<option value="newyork">New York</option>
<option value="london">London</option>
<option value="cardiff">Cardiff</option>
</select>

Now I need to work on the server side to set cookies to remember and redirect to a visited subdomain. It is working partially. The domain can redirect to the subdomain but keeps running repeatedly. How to stop the loop? Any help will be very much appreciated.

<?php
if (isset($_COOKIE["city"])) {
if ($_COOKIE["city"] == 'city') {
header("Location: http://{$_COOKIE["city"]}.example.com");
}
}
?>

You can add a checking of existing sub-domain, so it only redirect when the current site is not the target ‘city’.


<?php
if (isset($_COOKIE["city"])) {

    [B]$subdomain = array_shift(explode(".",$_SERVER['HTTP_HOST']));[/B]

    if ($_COOKIE["city"] == 'city'[B] && $_COOKIE["city"] != $subdomain[/B]) {
        header("Location: http://{$_COOKIE["city"]}.example.com");
    }
}
?>

Thanks hkmars. I just tested it but the cookie is not working and the domain cannot redirect to sub-domain when I type on the web browser. I am currently working on other codes but with no luck. Can you fix it?

<?php 
$hour = time() + 50400;  
setcookie(My_Site_Location, $_POST['citygo'], $hour); 

//Cookie
$Loc=$_COOKIE["city"]; 
if(isset($_POST['city'])) 
$Loc=$_POST['city']; 

if (empty($Loc)) { 
    header("Location: http://{$_COOKIE["city"]}.example.com");  
    } else { 
    header("Location: example.com/$Loc.php");  
}

or

<?php 
$hour = time() + 50400;  //Time you want the cookie to last, currently 14 hours 
setcookie(My_Site_Location, $_SERVER['citygo'], $hour, '/', 'example.com');

if (isset($_SERVER['citygo'])) {
   $cookies = explode(';', $_SERVER['citygo']);
   foreach ($cookies as $cookie) {
       list($cookie_id, $cookie_value) = explode('=', $cookie);
       if($cookie_id === $name){
          self::set_cookie($cookie_id, $value, $expiry, $path, $domain);
       }
   }
}
?>

PHP cookie is not cross sub-domains by default.

You can set it by ini_set function or in your php.ini file.


    ini_set("session.cookie_domain", ".example.com");

(with the “dot” before domain name means work for all root domain and sub-domains)

Let’s see if the following code will work for you.


<?php
ini_set("session.cookie_domain", ".example.com");

// Set cookie and redirect when user change city
if( isset($_POST['city']) && $_POST['city'] != '' ){
    $cookie_expire = time() + 50400;
    setcookie('city', $_POST['city'], $cookie_expire, '/');

    header("Location: http://".$_POST["city"].".example.com");
    die();
}

// Redirect if user selected default city
if (isset($_COOKIE["city"])) {
    $subdomain = array_shift(explode(".",$_SERVER['HTTP_HOST']));

    if ($_COOKIE["city"] != $subdomain) {
        header("Location: http://".$_COOKIE["city"].".example.com");
        die();
    }
}

Only replace example.com to your domain and don’t change the $_SERVER[‘HTTP_HOST’], as it is use to get the domain.

This is so strange. I don’t understand but still the same.

Maybe you should make sure the cookie is working by using some testing script.

e.g.

setcookie.php


<?php
  $cookie_expire = time() + 50400;
  setcookie('city', 'newyork', $cookie_expire, '/', '.example.com');
?>

getcookie.php


<?php
  echo 'city cookie is '.$_COOKIE["city"];
?>

Run setcookie.php in main domain, then run getcookie.php in city’s domain to see the result… is it showing ‘newyork’?

The testing script are working nicely. I have put the script below to both main domain and city’s domain yesterday. That could be why it was not working. Should I separate the script for 2 domains or you need to make some changes first? Thanks.

<?php 
ini_set("session.cookie_domain", ".example.com"); 

// Set cookie and redirect when user change city 
if( isset($_POST['city']) && $_POST['city'] != '' ){ 
    $cookie_expire = time() + 50400;  
    setcookie('city', $_POST['city'], $cookie_expire, '/'); 

    header("Location: http://".$_POST["city"].".example.com"); 
    die(); 
} 

// Redirect if user selected default city 
if (isset($_COOKIE["city"])) { 
    $subdomain = array_shift(explode(".",$_SERVER['HTTP_HOST'])); 

    if ($_COOKIE["city"] != $subdomain) { 
        header("Location: http://".$_COOKIE["city"].".example.com"); 
        die(); 
    } 
}

What’s wrong with this?
Thank you for posting! Your post will not be visible until a moderator has approved it for posting.

Your posts have landed in the moderation queue.

It could be something to do with the partial links you posted e.g.

header("Location: http://".$_COOKIE["city"].".example.com"); 

In an ideal world this shouldn’t happen, but this measure was taken to filter out a lot of spam we were receiving.

Anyway, I apologize for the confusion.
I can’t promise it won’t happen again, but I’m subscribed to this thread now, so will keep an eye on it :slight_smile: