Cookie.php 1.48 KB
<?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);
    }
}