如何在cakephp 4 版本中全局使用cookie 值?

How to use cookie value globally in cakephp 4 version?

我想在一个函数中设置 cookie 值,并且它们的值在 cakephp 4 版本中无处不在。 目前,我可以在唯一一个设置了值的函数中使用 cookie 值。

使用App\Controller\AppController;

使用Cake\Http\Cookie\Cookie;

使用Cake\Http\Cookie\CookieCollection

使用日期时间;

class AdminController 扩展 AppController {

function index(){
 $cookie = array();
 $cookie['admin_username'] = $requestData['username'];
 $cookie['admin_password'] = $requestData['password'];
 $cookies = new Cookie('AuthAdmin',$cookie, new DateTime('+1 weeks'));
 $response = $this->response->withCookie($cookie);
 return $this->redirect('admin/viewusers');
}

function viewusers() {
$cookies = new CookieCollection();
$data = $cookies->get('AuthAdmin');
print_r($data);
// cookie value not found in $data variable.
$response = $this->response->getCookie('Auth.Admin');
print_r($response);
// cookie value not found in $response variable.
}

}

试试这个:

function index(){
    $cookie = array();
    $cookie['admin_username'] = $requestData['username'];
    $cookie['admin_password'] = $requestData['password'];
    $cookies = new Cookie('AuthAdmin',$cookie, new DateTime('+1 weeks'));
    return $this
        // redirect returns a response object, so you can chain the cookie call onto that
        ->redirect('admin/viewusers')
        // Note that this uses $cookies, not $cookie
        ->withCookie($cookies);
}

但我再次强调,从安全角度来看,发送包含用户用户名和密码的 cookie 是一件非常糟糕的事情。