审查视图

thinkphp/library/think/Cookie.php 7.5 KB
王智 authored
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

namespace think;

class Cookie
{
    /**
     * @var array cookie 设置参数
     */
    protected static $config = [
        'prefix'    => '', // cookie 名称前缀
        'expire'    => 0, // cookie 保存时间
        'path'      => '/', // cookie 保存路径
        'domain'    => '', // cookie 有效域名
        'secure'    => false, //  cookie 启用安全传输
        'httponly'  => false, // httponly 设置
        'setcookie' => true, // 是否使用 setcookie
    ];

    /**
     * @var bool 是否完成初始化了
     */
    protected static $init;

    /**
     * Cookie初始化
     * @access public
     * @param  array $config 配置参数
     * @return void
     */
    public static function init(array $config = [])
    {
        if (empty($config)) {
            $config = Config::get('cookie');
        }

        self::$config = array_merge(self::$config, array_change_key_case($config));

        if (!empty(self::$config['httponly'])) {
            ini_set('session.cookie_httponly', 1);
        }

        self::$init = true;
    }

    /**
     * 设置或者获取 cookie 作用域(前缀)
     * @access public
     * @param  string $prefix 前缀
     * @return string|
     */
    public static function prefix($prefix = '')
    {
        if (empty($prefix)) {
            return self::$config['prefix'];
        }

        return self::$config['prefix'] = $prefix;
    }

    /**
     * Cookie 设置、获取、删除
     * @access public
     * @param  string $name   cookie 名称
     * @param  mixed  $value  cookie 值
     * @param  mixed  $option 可选参数 可能会是 null|integer|string
     * @return void
     */
    public static function set($name, $value = '', $option = null)
    {
        !isset(self::$init) && self::init();

        // 参数设置(会覆盖黙认设置)
        if (!is_null($option)) {
            if (is_numeric($option)) {
                $option = ['expire' => $option];
            } elseif (is_string($option)) {
                parse_str($option, $option);
            }

            $config = array_merge(self::$config, array_change_key_case($option));
        } else {
            $config = self::$config;
        }

        $name = $config['prefix'] . $name;

        // 设置 cookie
        if (is_array($value)) {
            array_walk_recursive($value, 'self::jsonFormatProtect', 'encode');
            $value = 'think:' . json_encode($value);
        }

        $expire = !empty($config['expire']) ?
        $_SERVER['REQUEST_TIME'] + intval($config['expire']) :
        0;

        if ($config['setcookie']) {
            setcookie(
                $name, $value, $expire, $config['path'], $config['domain'],
                $config['secure'], $config['httponly']
            );
        }

        $_COOKIE[$name] = $value;
    }

    /**
     * 永久保存 Cookie 数据
     * @access public
     * @param  string $name   cookie 名称
     * @param  mixed  $value  cookie 值
     * @param  mixed  $option 可选参数 可能会是 null|integer|string
     * @return void
     */
    public static function forever($name, $value = '', $option = null)
    {
        if (is_null($option) || is_numeric($option)) {
            $option = [];
        }

        $option['expire'] = 315360000;

        self::set($name, $value, $option);
    }

    /**
     * 判断是否有 Cookie 数据
     * @access public
     * @param  string      $name   cookie 名称
     * @param  string|null $prefix cookie 前缀
     * @return bool
     */
    public static function has($name, $prefix = null)
    {
        !isset(self::$init) && self::init();

        $prefix = !is_null($prefix) ? $prefix : self::$config['prefix'];

        return isset($_COOKIE[$prefix . $name]);
    }

    /**
     * 获取 Cookie 的值
     * @access public
     * @param string      $name   cookie 名称
     * @param string|null $prefix cookie 前缀
     * @return mixed
     */
    public static function get($name = '', $prefix = null)
    {
        !isset(self::$init) && self::init();

        $prefix = !is_null($prefix) ? $prefix : self::$config['prefix'];
        $key    = $prefix . $name;

        if ('' == $name) {
            // 获取全部
            if ($prefix) {
                $value = [];

                foreach ($_COOKIE as $k => $val) {
                    if (0 === strpos($k, $prefix)) {
                        $value[$k] = $val;
                    }

                }
            } else {
                $value = $_COOKIE;
            }
        } elseif (isset($_COOKIE[$key])) {
            $value = $_COOKIE[$key];

            if (0 === strpos($value, 'think:')) {
                $value = json_decode(substr($value, 6), true);
                array_walk_recursive($value, 'self::jsonFormatProtect', 'decode');
            }
        } else {
            $value = null;
        }

        return $value;
    }

    /**
     * 删除 Cookie
     * @access public
     * @param  string      $name   cookie 名称
     * @param  string|null $prefix cookie 前缀
     * @return void
     */
    public static function delete($name, $prefix = null)
    {
        !isset(self::$init) && self::init();

        $config = self::$config;
        $prefix = !is_null($prefix) ? $prefix : $config['prefix'];
        $name   = $prefix . $name;

        if ($config['setcookie']) {
            setcookie(
                $name, '', $_SERVER['REQUEST_TIME'] - 3600, $config['path'],
                $config['domain'], $config['secure'], $config['httponly']
            );
        }

        // 删除指定 cookie
        unset($_COOKIE[$name]);
    }

    /**
     * 清除指定前缀的所有 cookie
     * @access public
     * @param  string|null $prefix cookie 前缀
     * @return void
     */
    public static function clear($prefix = null)
    {
        if (empty($_COOKIE)) {
            return;
        }

        !isset(self::$init) && self::init();

        // 要删除的 cookie 前缀,不指定则删除 config 设置的指定前缀
        $config = self::$config;
        $prefix = !is_null($prefix) ? $prefix : $config['prefix'];

        if ($prefix) {
            foreach ($_COOKIE as $key => $val) {
                if (0 === strpos($key, $prefix)) {
                    if ($config['setcookie']) {
                        setcookie(
                            $key, '', $_SERVER['REQUEST_TIME'] - 3600, $config['path'],
                            $config['domain'], $config['secure'], $config['httponly']
                        );
                    }

                    unset($_COOKIE[$key]);
                }
            }
        }
    }

    /**
     * json 转换时的格式保护
     * @access protected
     * @param  mixed  $val  要转换的值
     * @param  string $key  键名
     * @param  string $type 转换类别
     * @return void
     */
    protected static function jsonFormatProtect(&$val, $key, $type = 'encode')
    {
        if (!empty($val) && true !== $val) {
            $val = 'decode' == $type ? urldecode($val) : urlencode($val);
        }
    }
}