今天在工做中,遇到了這樣一個問題。關於COOKIE的加密儲存;下面介紹下,如何實現最新瀏覽記錄:用戶的最新瀏覽記錄分爲:用戶登陸和用戶未登陸的狀況;用戶登陸後,除了寫COOKIE,還要存儲在數據表當中,爲了保證用戶在其餘的電腦上登陸,仍然可以查看以前的瀏覽記錄。代碼以下: php
static public function setUserNewBroswer($id,$data){ $tempNumber = 10; $data = $id."|".safe_replace($data); $user_info = $_SESSION['login_user']; $user_arr = explode("|", $user_info); $user_id = $user_arr[1]; $user_name = $user_arr[0]; $cookie_name = "wk_search".(empty($user_id)?"":base64_encode($user_id."+".$user_name."+")); $user_search_record = isset($_COOKIE[$cookie_name]) ? explode(",",trim(base64_decode(trim($_COOKIE[$cookie_name],",")))) : array(); if(count($user_search_record) >= $tempNumber){ array_shift($user_search_record); if(!in_array(trim($data),$user_search_record)){ $user_search_record[] = $data; } }else{ if(!in_array(trim($data), $user_search_record)){ $user_search_record[] = $data; } } $cookie_value = base64_encode(implode(",",$user_search_record)); setcookie($cookie_name,$cookie_value,time()+3600*24*30,"/"); if(!empty($user_info)){ $user_arr = explode("|", $user_info); $user_id = $user_arr[1]; $search_cookie = serialize($user_search_record); $dblink = new DataBase(""); $exist = Wk::isExistUserSearch($user_id); if($exist){ $dblink->query("UPDATE wk_search SET user_search='$search_cookie' WHERE user_id='$user_id'"); }else{ $dblink->query("INSERT INTO wk_search(user_id,user_search) VALUES('$user_id','$search_cookie')"); } } }那麼獲取COOKIE的代碼以下:
static public function getUserNewBrowser(){ $user_info = $_SESSION['login_user']; $user_arr = explode("|", $user_info); $user_id = $user_arr[1]; $user_name = $user_arr[0]; $dblink = new DataBase(""); if($user_info){ $rs = $dblink->getRow("SELECT user_search FROM wk_search WHERE user_id='$user_id'"); if(!empty($rs)){ return unserialize($rs[0]['user_search']); }else{ return array(); } }else{ $cookie_name = "wk_search".(empty($user_id)?"":base64_encode($user_id."+".$user_name."+")); $cookie = base64_decode(trim($_COOKIE[$cookie_name],",")); return $cookie ? explode(",", $cookie) : array(); } }須要注意的地方:
<1>序列化存儲的時候,用於須要保存最新的10條數據記錄,則須要數據表的對應的字段的長度足夠大,不然,會出現serialize序列化後的字符串不完整的狀況。 cookie
<2>在字符串入列的時候,注意清除字符串左右兩邊的空格。 加密
<3>在使用base64_encode()進行加密的時候,在獲取cookie的時候,須要清除字符串左右兩邊的空格。 spa
<4>對於頁面顯示的倒序,在調用的模板頁面,利用array_reverse就能夠。 code