/** * Get value of HTTP cookie from the current HTTP request * * Return the value of a cookie from the current HTTP request, * or return NULL if cookie does not exist. Cookies created during * the current request will not be available until the next request. * * @param string $name * @param bool $deleteIfInvalid doing delete if invalid * @param bool $encrypted use force encryped to set true if encrypted * without following config * set to false if use no encryption * @return string|null */ public static function get($name, $deleteIfInvalid = false, $encrypted = null) { // Get cookie value $cookies = Request::cookies(); $value = $cookies->get($name); $config = Config::singleton(); $prefix = $config->get('cookie_encrypt_prefix', 'enc|'); is_string($prefix) && trim($prefix) || ($prefix = 'enc|'); // Decode if encrypted if (($config->get('cookie_encrypt', true) && $encrypted !== false || $encrypted) && strpos($value, $prefix) === 0) { $value = Security::decrypt($value, sha1($config->security_key . $config->security_salt . $config->session_hash)); if ($value === null && $deleteIfInvalid) { static::deleteCookie($name); } } return $value; }
/** * Serialize Response cookies into raw HTTP header * * @param \Enproject\ErSysDucation\Response\Header $header The Response header */ public static function serializeCookies(Headers &$header) { $instance = static::singleton(); $config = Config::singleton(); $cookies = $instance->cookies(); $prefix = $config->get('cookie_encrypt_prefix', 'enc|'); is_string($prefix) && trim($prefix) || ($prefix = 'enc|'); $config->cookie_encrypt = $config->get('cookie_encrypt', true); foreach ($cookies as $name => $settings) { if (is_string($settings['expires'])) { $expires = strtotime($settings['expires']); } else { $expires = (int) $settings['expires']; } /** * Check if is has encrypted value * if config cookie encrypt has true * and * (__ settings['encrypted'] = has null or not exists) * or not empty $settings['encrypted'] * @var boolean */ if (!empty($settings['encrypted']) || $config->cookie_encrypt && !isset($settings['encrypted'])) { // add prefix enc to make sure if cookie has encrypt $settings['value'] = $prefix . Security::encrypt($settings['value'], Sha1::hash($config->security_key . $config->security_salt . $config->session_hash)); } /** * Cookie only accept 4KB */ if (strlen($settings['value']) > 4096) { ErrorHandler::set(E_USER_WARNING, sprintf('Cookie %s has been generate more than 4KB failed to save! if there was cookie before, it will be not replaced!', $name), __FILE__, __LINE__); } else { // set header cookies static::setCookieHeader($header, $name, $settings); } } }