1. Go to this page and download the library: Download rubyan/cake3-cookieauth library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
php
public function beforeFilter(Event $event) {
//Automaticaly Login.
if (!$this->Auth->user() && $this->Cookie->read('CookieAuth')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
} else {
$this->Cookie->delete('CookieAuth');
}
}
}
//If you want to update some fields, like the last_login_date, or last_login_ip, just do :
public function beforeFilter(Event $event) {
//Automaticaly Login.
if (!$this->Auth->user() && $this->Cookie->read('CookieAuth')) {
$this->loadModel('Users');
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
$user = $this->Users->newEntity($user);
$user->isNew(false);
//Last login date
$user->last_login = new Time();
//Last login IP
$user->last_login_ip = $this->request->clientIp();
//etc...
$this->Users->save($user);
} else {
$this->Cookie->delete('CookieAuth');
}
}
}
php
//It will write Cookie without RememberMe checkbox
$this->Cookie->configKey('CookieAuth', [
'expires' => '+1 year',
'httpOnly' => true
]);
$this->Cookie->write('CookieAuth', [
'username' => $this->request->data('username'),
'password' => $this->request->data('password')
]);
//If you want use a RememberMe checkbox in your form :
//In your view
echo $this->Form->checkbox('remember_me');
//In the login action :
if($this->request->data('remember_me')) {
$this->Cookie->configKey('CookieAuth', [
'expires' => '+1 year',
'httpOnly' => true
]);
$this->Cookie->write('CookieAuth', [
'username' => $this->request->data('username'),
'password' => $this->request->data('password')
]);
}