Blame view

Hood/Cookie.php 1.48 KB
ziy 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
<?php
namespace Hood;

use Hood\Debug\DebugException;

class Cookie
{
    /**
     * 取得所有的cookie值
     *
     * @return array
     * @since 0.2.2
     */
    public static function all()
    {
        return $_COOKIE;
    }

    /**
     * @param $name
     * @param string $default
     * @return string
     * @throws DebugException
     */
    public static function get($name, $default = '')
    {
        if (preg_match("/[=,; \t\r\n\013\014]/", $name)) {
            throw new DebugException(sprintf('The cookie name "%s" contains invalid characters.', $name));
        }
        return isset ($_COOKIE [$name]) ? $_COOKIE [$name] : $default;
    }

    /**
     * 设置cookie
     * @param string $name
     * @param string $domain
     * @param string $value
     * @param int $expire (0:Session、-1:删除、time():过期时间 )
     * @param string $path
     * @param bool $httponly
     * @param bool $secureAuto
     */
    public static function set($name, $value, $minutes = 0, $path = '/', $domain = null, $secure = false, $httpOnly = true)
    {
        if (preg_match("/[=,; \t\r\n\013\014]/", $name)) {
            throw new DebugException(sprintf('The cookie name "%s" contains invalid characters.', $name));
        }
        $expire = $minutes;
        if ($minutes == 0) {
            $expire = 0;
        } else if ($minutes == -1) {
            $expire = time() - 3600;
        }
        setcookie($name, $value, $expire, $path, $domain, (bool)$secure, $httpOnly);
    }
}