SafeCookie.class.php 1.62 KB
<?php
class Util_Utils_SafeCookie {
    private static $cookie = null;
    private static function cookie() {
        if(!isset($cookie)) {
            self::$cookie = new Util_Cookie();
        }
        return self::$cookie;
    }
    
    /**
     * 设置
     * 
     * @param string $key
     * @param array|string $value
     * @param int $expire
     * @param string $domain
     * @return boolean
     */
    public static function set($key, $value, $expire = 1209600, $domain = '') {
       if(is_array($value)) {
            $value = json_encode($value);
       }
       //默认整个域
       if(empty($domain)) {
            $domain = strstr($_SERVER['HTTP_HOST'], '.');
       }
       //设置时效,默认两周
       return self::cookie()->setName($key)->setExpire($expire)->setDomain($domain)->setPath('/')->setValue(Util_Utils_AuthCode::encode($value, $key))->set();
    }
    
    /**
     * 获取
     * 
     * @param string $key
     * @return array|string
     */
    public static function get($key) {
        $value = self::cookie()->get($key);
        $value = Util_Utils_AuthCode::decode($value, $key);
        $var = json_decode($value, true);
        return empty($var)? $value: $var; 
    }
    
    /**
     * 清除
     * 
     * @param string $key
     * @param string $domain
     * @return boolean
     */
    public static function clear($key, $domain = '') {
        //默认整个域
        if(empty($domain)) {
            $domain = strstr($_SERVER['HTTP_HOST'], '.');
        }
        return self::cookie()->setName($key)->setExpire(-1)->setPath('/')->setDomain($domain)->setValue('')->set();
    }
    

}