在 PHP 開發中,Cookie 是實現用戶狀態保持、個性化設定等功能的核心機制。雖然 PHP 內建了 setcookie() 與 $_COOKIE 超全域變數,但在實際專案中往往需要更完善的功能:資料加密、自動序列化、前綴管理、過期時間控制等。本文將詳細介紹一個功能完整的 Cookies 類別,並提供實際應用範例。
authcode 演算法保障資料安全private $_prefix = ''; // Cookie 名稱前綴 private $_securekey = '...'; // 加密金鑰 private $_expire = 3600; // 預設過期秒數(1小時)
建構子允許一次性配置前綴、過期時間與金鑰:
public function __construct($prefix='', $expire=0, $securekey='') {
if (is_string($prefix) && $prefix!='') $this->_prefix = $prefix;
if (is_numeric($expire) && $expire>0) $this->_expire = $expire;
if (is_string($securekey) && $securekey!='') $this->_securekey = $securekey;
}
亦提供 setPrefix()、setExpire() 供執行期動態調整。
採用 JSON 格式封裝資料與過期時間戳:
private function pack($data, $expire) {
if ($data==='') return '';
return json_encode(['value' => $data, 'expire' => $expire]);
}
private function unpack($data) {
if ($data==='') return ['', 0];
$cookie_data = json_decode($data, true);
if (isset($cookie_data['value'], $cookie_data['expire']) && time() < $cookie_data['expire']) {
return [$cookie_data['value'], $cookie_data['expire']];
}
return ['', 0];
}
authcode() 採用經典的 Discuz! 風格對稱加密演算法,支援 ENCODE/DECODE 雙模式,包含隨機金鑰、時間戳驗證、資料完整性校驗等機制,有效防範竄改與重放攻擊。
require 'Cookies.class.php';
$type = isset($_GET['type']) ? strtolower($_GET['type']) : '';
if (!in_array($type, ['set','get','update','clear'])) exit('type not exists');
$obj = new Cookies('member', 10); // 前綴 member,預設 10 秒過期
switch ($type) {
case 'set':
$data = ['name' => 'fdipzone', 'gender' => 'male'];
$obj->set('me', $data, 5); // 覆蓋預設,設為 5 秒
echo 'set cookies';
break;
case 'get':
$result = $obj->get('me');
echo ''; print_r($result); echo '
';
echo 'get cookies';
break;
case 'update':
$data = ['name' => 'angelababy', 'gender' => 'female'];
$flag = $obj->update('me', $data);
echo $flag ? 'update cookies success' : 'update cookies false';
break;
case 'clear':
$obj->clear('me');
echo 'clear cookies';
break;
}
$obj->set('user', $userObject); 會自動序列化setcookie 第 5 參數 domain 需自行擴展類別set() 方法加入第 6、7 參數此 Cookies 類別解決了原生操作的諸多痛點,特別是加密、序列化、前綴管理三大實用功能,可直接投入生產環境。開發者可根據專案需求擴展 HttpOnly、SameSite 等現代 Cookie 屬性,進一步提升安全性。