首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP Cookies 操作類:加密存儲、前綴隔離、強制過期控制

     編輯:PHP 綜合知識

核心功能

  • 資料型別透明支援:字串、陣列、物件自動序列化
  • 自動加密/解密 (authcode),防竄改
  • 前綴隔離避免衝突
  • 強制過期時間控制
  • 完整 CRUD:set/get/update/clear

關鍵實現細節

<?php
class Cookies {
    private $_prefix = '';
    private $_securekey = 'ekOt4_Ut0f3XE-fJcpBvRFrg506jpcuJeixezgPNyALm';
    private $_expire = 3600;

    public function set($name, $value, $expire=0) {
        $cookie_name = $this->_getName($name);
        $cookie_expire = time() + ($expire ?: $this->_expire);
        $cookie_value = $this->_pack($value, $cookie_expire);
        $cookie_value = $this->_authcode($cookie_value, 'ENCODE', $this->_securekey);
        setcookie($cookie_name, $cookie_value, $cookie_expire);
    }

    public function get($name) {
        $cookie_name = $this->_getName($name);
        if (isset($_COOKIE[$cookie_name])) {
            $val = $this->_authcode($_COOKIE[$cookie_name], 'DECODE', $this->_securekey);
            $val = $this->_unpack($val);
            return $val[0] ?? null;
        }
        return null;
    }

    private function _pack($data, $expire) {
        return serialize([$data, $expire]);
    }
    private function _unpack($data) {
        return @unserialize($data) ?: [null, 0];
    }
    // ... update, clear, setPrefix, setExpire, _getName, _authcode
}
?>

使用示例

<?php
$cookie = new Cookies('myapp_', 7200); // 前綴 myapp_,預設 2 小時

$cookie->set('user', ['id'=>1001, 'name'=>'fdipzone', 'roles'=>['admin','editor']]);
$user = $cookie->get('user'); // 陣列自動還原

$cookie->update('user', ['id'=>1001, 'name'=>'fdipzone', 'roles'=>['admin']]); // 僅更新值保留過期時間
$cookie->clear('user');
?>

安全提示:生產環境請更換預設 _securekey,並啟用 HTTPS + Secure/HttpOnly 旗標。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved