Introduction
The following piece of code will calculate the last visited time of a Member/User and
calculate the time difference with the current time. And if the Member/User's last visited time is greater than 10 minutes then that will be considered OFFLINE
status, otherwise ONLINE.
Background
I was just searching for a time difference code in Bakery but couldn't find
any simple code. I developed and used the following code to calculate the time a User/Member is online or offline.
Using the code
There are only three steps to follow. This code is only for CakePHP 1.5.
"I am assuming that you have a table named MEMBER (you can customize it according to your requirements)".
- Make a field
last_visit
(DATETIME
) in MEMBER table. - For app controller:
class AppController extends Controller {
function beforeRender()
{
### UPDATE LAST VISIT ###
$online_offline_status = 0;
if ($this->Session->check('userId')==true){
$this->loadModel('Member');
$last_visit = date('Y-m-d H:i:s', time());
$this->Member->updateAll(array('Member.last_visit' => '"'.$last_visit.'"'),
array('Member.id' => $this->Session->read('userId')));
$member_last_visit = $this->Member->find('first', array('conditions' =>
array('Member.id' => $this->Session->read('userId'))));
$current_time = strtotime(date("Y-m-d H:i:s"));
$last_visit = strtotime($member_last_visit['Member']['last_visit']);
$time_period = floor(round(abs($current_time - $last_visit)/60,2));
echo $time_period;
if ($time_period <= 10){
$online_offline_status = 1;
} else {
$online_offline_status = 0;
}
}
$this->set('online_offline_status', $online_offline_status);
}
}
- Simply use the following code in your .ctp file according to your demand.
<!-- IF USER IS OFFLINE -->
if ($online_offline_status == 0){
echo '(Member/User is Offline)';
<!-- IF USER IS OFFLINE -->
} else if ($online_offline_status == 1) {
echo '(Member/User is Online)';
}