php Implementation to Obtain and Set User Access Page Language Class
- 2021-07-21 07:41:06
- OfStack
This article describes the example of php to achieve access to and set the user access to the page language class, to share for your reference. The specific analysis is as follows:
The instance User Language Class gets/sets the page language accessed by the user, and reads Accept-Language if the user does not set the access language. Display the corresponding page according to the language selected by the user (English, Simplified Chinese, Traditional Chinese)
The UserLang. class. php class files are as follows:
<?php
/** User Language Class Get / Set the page language accessed by the user, and if the user does not set the access language, read Accept-Language
* Date: 2014-05-26
* Author: fdipzone
* Ver: 1.0
*
* Func:
* public get Get the user access language
* public set Setting User Access Language
* private getAcceptLanguage Get HTTP_ACCEPT_LANGUAGE
*/
class UserLang{ // class start
private $name = 'userlang'; // cookie name
private $expire = 2592000; // cookie expire 30 days
/** Initialization
* @param String $name cookie name
* @param int $expire cookie expire
*/
public function __construct($name='', $expire=null){
// Settings cookie name
if($name!=''){
$this->name = $name;
}
// Settings cookie expire
if(is_numeric($expire) && $expire>0){
$this->expire = intval($expire);
}
}
/** Get the user access language */
public function get(){
// Determine whether the user has set the language
if(isset($_COOKIE[$this->name])){
$lang = $_COOKIE[$this->name];
}else{
$lang = $this->getAcceptLanguage();
}
return $lang;
}
/** Setting User Access Language
* @param String $lang User access language
*/
public function set($lang=''){
$lang = strtolower($lang);
// English, Simplified Chinese, Traditional Chinese only
if(in_array($lang, array('en','sc','tc'))){
setcookie($this->name, $lang, time()+$this->expire);
}
}
/** Get HTTP_ACCEPT_LANGUAGE */
private function getAcceptLanguage(){
$lang = strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']);
if(in_array(substr($lang,0,5), array('zh-tw','zh_hk'))){
$lang = 'tc';
}elseif(in_array(substr($lang,0,5), array('zh-cn','zh-sg'))){
$lang = 'sc';
}else{
$lang = 'en';
}
return $lang;
}
} // class end
?>
The demo sample program is as follows:
<?php
require "UserLang.class.php";
$obj = new UserLang('sitelang', 3600);
echo $obj->get().'<br>';
?>
I hope this article is helpful to everyone's study of PHP programming.