【问题标题】:How to use cookie value globally in cakephp 4 version?如何在 cakephp 4 版本中全局使用 cookie 值?
【发布时间】:2021-11-22 19:20:55
【问题描述】:

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

  • 我可以在 index() 函数中获取 cookie 值,但我无法在 viewusers() 函数中获取 cookie 值。 代码在这里:

使用 App\Controller\AppController;

使用 Cake\Http\Cookie\Cookie;

使用 Cake\Http\Cookie\CookieCollection

使用日期时间;

类 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.
}

}

  • 我可以在 index() 函数中获取 cookie 值,但我无法在 viewusers() 函数中获取 cookie 值。

【问题讨论】:

  • 你的意思是你想在同一个请求中设置然后在其他功能中使用它(例如在控制器中设置它然后在模板中引用它)?或者在一个请求中设置它,然后在以后的请求中引用它(例如,在用户登录时设置它,然后在查看或编辑记录时再次引用它)?请分享您用于设置 cookie 的代码。
  • 代码在这里:class AdminController extends AppController { function index(){ $cookie = array(); $cookie['admin_username'] = $requestData['username']; $cookie['admin_password'] = $requestData['password']; $cookies = new Cookie('AuthAdmin',$cookie, new DateTime('+1 周')); } function viewusers() { $cookies = new CookieCollection(); $data = $cookies->get('AuthAdmin');打印_r($数据); // 在 $data 变量中找不到 cookie 值。我可以在 index() 函数中获取 cookie 值,但我无法在 viewusers() 函数中获取 cookie 值。
  • 您已经创建了一个 Cookie 对象。您尚未将其添加到响应中。但是将这类信息放在 cookie 中是一种非常糟糕的安全做法!您可能打算将其写入会话?
  • 我试图将它添加到响应中,但我仍然得到空 cookie 值。响应添加如下: $response = $this->response->withCookie($cookie);并获取 cookie 值,例如: $this->response->getCookie($cookiename);
  • 您是否从控制器返回了这个新的响应对象?您真的确定要发送包含用户密码的 cookie 吗?

标签: cookies setcookie cakephp-4.x


【解决方案1】:

试试这个:

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 是一件非常糟糕的事情。

【讨论】:

    猜你喜欢
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 2020-08-20
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多