DALLASCAO.COM

Site of Cao Shouguang, English to Chinese translator

Use cookies to remember the language version users visited last time (php code)

This site is bilingual. http://dallascao.com/cn/ is the Chinese version and http://dallscao.com/en/ is the English version. When you visit http://dallascao.com/, you are directed to either /cn/ or /en/ according to the default language of your browser or the version you visited last time. The site uses cookies to remember the version you visited last time and direct you to that version when you visit again. If it is the first time to visit, you will open the version that matches your browser language.

To do this, you need to edit the header.php of the English version under the /en/ folder and add the following code before the tag:



This code writes a variable “lang” on your computer and assigns a value “en”. 94608000 is the expiration time (3 years). “/” and “.dallascao.com” means it works from the root directory of dallascao.com and its subdomains. Inserting this code into header.php means that when you visit any page of the English version, your visit will be remembered.

Likewise, you need to insert the following code into the header.php of the Chinese version.



It means when you visit the Chinese version, the variable “lang” will be assigned the value of “cn”.

At last, Create an index.php at the root containing the following code.




 1)  {
      # Split possible languages into array
      $x = explode(",",$http_accept);
      foreach ($x as $val) {
         #check for q-value and create associative array. No q-value means 1 by rule
         if(preg_match("/(.*);q=([0-1]{0,1}\.\d{0,4})/i",$val,$matches))
            $lang[$matches[1]] = (float)$matches[2];
         else
            $lang[$val] = 1.0;
      }

      #return default language (highest q-value)
      $qval = 0.0;
      foreach ($lang as $key => $value) {
         if ($value > $qval) {
            $qval = (float)$value;
            $deflang = $key;
         }
      }
   }
   return strtolower($deflang);
}


?>

Leave a Comment