Search code examples
cookiessetcookiecakephp-4.x

How to use cookie value globally in cakephp 4 version?


I want to set cookie value in one function and their value use everywhere in cakephp 4 version. Currently , i can use cookie value inside the only one function which i have set their value.

  • I can get cookie value in index() function but i can't get cookie value in viewusers() function. Code is here :

use App\Controller\AppController;

use Cake\Http\Cookie\Cookie;

use Cake\Http\Cookie\CookieCollection

use DateTime;

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

}

  • I can get cookie value in index() function but i can't get cookie value in viewusers() function.

Solution

  • Try this:

    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);
    }
    

    But again, I cannot stress strongly enough that sending a cookie with the user's username and password in it is a very bad thing from a security perspective.