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");
}
}
?>
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?
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();
}
}