ctms/common/components/HiCookie.php
2025-04-10 23:19:13 +08:00

67 lines
1.7 KiB
PHP
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* @Author: fm453
* @Date: 2021-09-08 00:25:51
* @Last Modified by: fm453
* @Last Modified time: 2021-09-09 02:03:09
* @Email: fm453@lukegzs.com
*/
namespace common\components;
use Yii;
class HiCookie {
//添加Cookie
public static function set($name,$value,$httpOnly=true,$expire=null)
{
$cookie = new \yii\web\Cookie();
$cookie->name = $name; //cookie的名称
$expire = $expire>0 ? $expire : '180'; //默认180s
$cookie->expire = time() + $expire; //存活的时间
$cookie->httpOnly = $httpOnly; //无法通过js读取cookie
$cookie->value = $value; //cookie的值
\Yii::$app->response->getCookies()->add($cookie);
}
//读取Cookie
public static function get($name)
{
if(\Yii::$app->request->cookies->has($name)){
return \Yii::$app->request->cookies->getValue($name);
}
return false;
}
public static function getObj($name)
{
if(\Yii::$app->request->cookies->has($name)){
return \Yii::$app->request->cookies->get($name);
}
return false;
}
//删除Cookie /*注意删除用的是response而不是request*/
public static function delete($name)
{
$cookie = $this->getObj($name);
//移除一个Cookie对象
if($cookie){
\Yii::$app->response->getCookies()->remove($cookie);
}
}
public static function deleteAll()
{
//移除所有Cookie目前好像不太好使
\Yii::$app->response->getCookies()->removeAll();
}
//读取Cookie的总数
public static function count()
{
return \Yii::$app->request->cookies->count();
}
}