I'm needing help with trying to display the users last online time.
My aim is to make it so that if the users status is 'online', display last seen just now, else, display the last time they were seen. Or if it's better, just display their last online time including seconds.
My code works but for some reason, when the user is offline, it displays user last online 1 hour ago if it I logged out less than 10 seconds ago.
My code is below
//Our default online script to get the last active time period from our lastactive time
function time_since($since)
{
global $con;
global $user_infos;
foreach($user_infos as $user)
{
$last_active = $user[7];
$user_status = $user[6];
$chunks = array(
array(60 * 60 * 24 * 365 , 'year'),
array(60 * 60 * 24 * 30 , 'month'),
array(60 * 60 * 24 * 7, 'week'),
array(60 * 60 * 24 , 'day'),
array(60 * 60 , 'hour'),
array(60 , 'minute'),
array(1 , 'second')
);
for ($i = 0, $j = count($chunks); $i < $j; $i++)
{
$seconds = $chunks[$i][0];
$name = $chunks[$i][1];
if (($count = floor($since / $seconds)) != 0)
{
break;
}
}
$print = ($count == 1) ? '1 '.$name : "$count {$name}s";
$check = $user_status == 'online' ? 'last online just now' : 'last online '.$print;
return $check;
}
}
// I made to make it firstly, update the users lastactive time for each page they go on by calling the function user_online_check() in the header (which is called for every page)
// and secondly, make it return a green image if the client is online and a red image if the client is offline
function user_online_check()
{
global $con;
global $user_infos;
global $time;
foreach($user_infos as $user)
{
$username = $_SESSION["user_i"];
$now = date("Y-m-d H:i:s");
//mysqli_query($con, "UPDATE users SET lastactive = NOW() WHERE username = '$username'");
$last_active = $user[7];
$user_status = $user[6];
mysqli_query($con, "UPDATE users SET status = 'offline' WHERE TIMESTAMPDIFF(MINUTE, lastactive, NOW()) > 1 AND username = '$username' LIMIT 1");
mysqli_query($con, "UPDATE users SET status = 'online' WHERE TIMESTAMPDIFF(MINUTE, lastactive, NOW()) < 1 AND username = '$username' LIMIT 1");
if($user_status == 'online')
{
echo '<center><img src="images/user/bullet_green.ico" style="width: 20px; height: 20px;" title="'.time_since(time() - strtotime($last_active)).'"></center>';
}
else if($user_status == 'offline')
{
echo '<center><img src="images/user/bullet_red.ico" style="width: 20px; height: 20px;" title="'.time_since(time() - strtotime($last_active)).'"></center>';
}
}
}
try this
$seen = floor((time("now")-$row['time'])/60);
$more = false;
if($seen > 60) {
$more = true;
$hours = floor($seen/60);
$minutes = $seen-($hours*60);
if(($seen > 24) && ($more == true)) {
$days = floor(($seen/60)/24);
$hours = floor($seen/60)-($days*24);
}
if($minutes == 1) {
$minute = ' minute ';
} else {
$minute = ' minutes ';
}
if($hours == 1) {
$hour = ' hour ';
} else {
$hour = ' hours ';
}
if($days == 1) {
$day = ' day ';
} else {
$day = ' days ';
}
if($days > 0) {
$seen = $days . $day . $hours . $hour . $minutes . $minute . 'ago';
} else {
$seen = $hours . $hour . $minutes . $minute . 'ago';
}
} else {
if($seen == 1) {
$minute = ' minute ';
} else {
$minute = ' minutes ';
}
$seen = $seen . $minute . 'ago';
}
Related
I'm working on a calendar for my office. Every people has his own column and there is a line for every day.
There are some periodic date, where, for example, given people have to be working on the week-end. But most of the dates are coming from a MySQL database.
So it does a double loop (people vs dates) in which every dates have to be check for the person, what kind of occupation he has on this day.
Is there a way to optimize this script, because online it take at least 2-3 seconds (only 0.03 seconds according to PHP, but I don't feel like it's correct) and more than 8 seconds (again according to PHP) on our network! And this is just for 5 months, we'd like to have it for the whole year.
You can find a test version here (just to see the HTML and CSS): http://mybees.ch/for/tableau.php
And here is the PHP in it:
//Creating the line for the collaborators
$ids;
$ma_count=0;
$ma_name_query = mysqli_query($bdi,"SELECT DISTINCT m.id, m.name, m.vorname, m.grup FROM ma m, ma_pos mp WHERE m.id = mp.maid AND m.grup != 14 ORDER BY m.grup, mp.posid, m.name, m.vorname");
while($ma_name = mysqli_fetch_assoc($ma_name_query)) {
echo '<div class="cell name">'.$ma_name['name'].' '.$ma_name['vorname'].'</div>';
$ids[$ma_count] = $ma_name['id'];
$grup[$ma_count] = $ma_name['grup'];
$ma_count++;
}
// Check if special group day
$firstGroup = 1;
$firstDate = strtotime("$year-01-01 00:00 GMT");
$picket = array();
if (date("N", $firstDate) == 2)// Tuesday
$firstDate -= 24 * 3600;
elseif (date("N", $firstDate) == 3)// Wednesday
$firstDate -= 2 * 24 * 3600;
elseif (date("N", $firstDate) == 5)// Friday
$firstDate -= 24 * 3600;
elseif (date("N", $firstDate) == 6)// Saturday
$firstDate -= 2 * 24 * 3600;
elseif (date("N", $firstDate) == 7)// Sunday
$firstDate -= 3 * 24 * 3600;
for ($date = $firstDate; $date <= strtotime("$year-12-31 00:00 GMT"); $date += 24 * 3600) {
$weekNb = date("W",$date);
$weekDay = date("N",$date); // Monday = 1, Sunday = 7
if ($weekDay < 4)
$group = $weekNb % 4 - 1 + $firstGroup;
else
$group = $weekNb % 4 - 2 + $firstGroup;
if ($group == 0)
$group = 4;
if ($group == -1)
$group = 3;
$picket[$date] = $group;
}
$groupColor = ["yellow", "blue", "red", "green"];
function isPicket($date, $grup) {
global $picket, $groupColor;
//global $picket, $groupColor;
if ($grup < 5) {
if ($picket[$date] == $grup)
return " style='background-color: ".$groupColor[$picket[$date]-1]."'";
}
}
$today_stp = time() - time() % (24 * 3600) - 11 * 24 * 3600;
$frei_query_text = "SELECT id_ma, date1, date2, free.id as type, moment, remark, location FROM frei, free WHERE free.id = frei.type AND date1 BETWEEN CAST('$date1' AS DATE) AND CAST('$date2' AS DATE)";
$frei_query = mysqli_query($bdi, $frei_query_text);
$free = array();
while($frei = mysqli_fetch_assoc($frei_query)) {
$free[] = $frei;
}
// Filling the lines
for ($date = strtotime($date1); $date <= strtotime($date2); $date += 24 * 3600) {
$today = ($date == $today_stp) ? ' id="today"':'';
echo "<div class='clear'$today>";
$class = (date('N', $date) < 6) ? 'week' : 'weekend';
echo "<div class='date $class line'>".date("D, d.m.", $date)."</div>";
for ($i = 0; $i < $ma_count; $i++) {
echo "<div class='cell line $class'".isPicket($date,$grup[$i]).">
<div class='small-cell".isColor($ids[$i], $date, 0)."' id='divUp-".$ids[$i]."-$date'> </div>
<div class='small-cell".isColor($ids[$i], $date, 1)."' id='divDown-".$ids[$i]."-$date'> </div>
</div>";
}
echo '</div>';
}
function isColor($id_ma, $date, $moment) {
global $free;
for ($i = 0; $i < count($free); $i++) {
if ($id_ma == $free[$i]['id_ma']) {
if ($date >= strtotime($free[$i]['date1']) && $date <= strtotime($free[$i]['date2'])) {
if ($free[$i]['moment'] == $moment || $free[$i]['moment'] == 2) {
$type = $free[$i]['type'];
$style = "";
if ($type > 1 && $type < 5)
$style = " urlaub";
if ($type > 4 && $type < 8)
$style = " frei";
if ($type > 7 && $type < 11)
$style = " ferien";
if (($type > 22 && $type < 34) || ($type > 37 && $type < 48))
$style = " kurse";
if ($type > 10 && $type < 17)
$style = " krank";
return " $style' title='".$free[$i]['remark'];
}
}
}
}
}
Thank you very much for your help
I have a challenge I am trying to add all the time the user has spent online but I am getting wrong totals. I am taking values from mysql database and I want to get total hours, minutes and seconds for each user. Currently I am getting totals for each session but now I want total for all sessions and display all users in a table where I have username and time spent online and must be able to filter results by date getting total time spent in hours, minutes and seconds for the filtered date. How can I do that. My code is as follows:
$i=0;
foreach ($report as $online)
{
$id = $online['userid'];
$sql = "SELECT start_time, end_time FROM user_sessions where userid=$id AND end_time !='0000-00-00' || end_time != '' LIMIT $start, $per_page";
$timeOnline = $obj->MySQLSelect($sql);
++$i;
$start = $timeOnline[$i]['start_time'];
$end = $timeOnline[$i]['end_time'];
$totalhours = get_saved_time($end, $dstart);
$sum = $totalhours;
?>
<tr class="gradeA">
<?php if (!empty($sum)): ?>
<td><? echo $generalobjAdmin->clearName($online['fname'].' '.$online['lname']); ?></td>
<td align="center"><?= Convert($sum); ?></td>
<?php endif; ?>
</tr>
<? } ?>
public function get_saved_time($end_time,$start_time)
{
$past = $start_time;
$current = strtotime($end_time);
$past = strtotime($past);
return round(abs($current-$past));
}
function Convert($seconds) {
$hours = floor($seconds / 3600);
$mins = floor(($seconds / 60) % 60);
$secs = $seconds % 60;
if (strlen($hours) == 1)
$hours = "0" . $hours;
if (strlen($secs) == 1)
$seconds = "0" . $secs;
if (strlen($mins) == 1)
$minutes = "0" . $mins;
if ($hours == 0){
$mint="";
$secondss="";
if($mins > 01){
$mint = "$mins mins";
}else{
$mint = "$mins min";
}
if($secs > 01){
$secondss = "$secs seconds";
}else{
$secondss = "$secs second";
}
$ret = "$mint $secondss";
} else {
$mint="";
$secondss="";
if($mins > 01){
$mint = "$mins mins";
}else{
$mint = "$mins min";
}
if($secs > 01){
$secondss = "$secs seconds";
}else{
$secondss = "$secs second";
}
if($hours > 01){
$ret = "$hours hrs $mint $secondss";
}else{
$ret = "$hours hr $mint $secondss";
}
}
return $ret;
}
How to get the total number of monts, days, and minutes from a given minute. Say for example given a value in minutes 93366 should return 2 months ,5 days and 5 hours. This is what I've tried so far.
function convert_minutes($minutes, $output) {
if ($minutes >= 43833) {
$whole_month = 0;
$decimal_month = 0;
$label = "";
$months = $minutes / 43833;
list($whole_month, $decimal_month) = sscanf($months, '%d.%d');
if ($months > 1) {
$label = "months";
} else {
$label = "month";
}
$output .= $months . " " . $label;
$decimal_month = "0." . $decimal_month;
if ($decimal_month != 0) {
return $this->convert_minutes($decimal_month, $output);
} else {
return $output;
}
} elseif ($minutes >= 1440) {
$whole_day = 0;
$decimal_day = 0;
$label = "";
$days = $minutes / 1440;
list($whole_day, $decimal_day) = sscanf($days, '%d.%d');
if ($days > 1) {
$label = "days";
} else {
$label = "day";
}
$output .= $days . " " . $label;
$decimal_day = "0." . $decimal_day;
if ($decimal_day != 0) {
return $this->convert_minutes($decimal_day, $output);
} else {
return $output;
}
} elseif ($minutes >= 60) {
$whole_minutes = 0;
$decimal_minutes = 0;
$label = "";
$min = $minutes / 60;
list($whole_minutes, $decimal_minutes) = sscanf($min, '%d.%d');
if ($min > 1) {
$label = "minutes";
} else {
$label = "minute";
}
$output .= $min . " " . $label;
$decimal_minutes = "0." . $decimal_minutes;
if ($decimal_minutes != 0) {
return $output . " and " . $decimal_minutes . " minutes";
} else {
return $output;
}
}
}
EDIT
I just wanted to get the estimate. Assuming 1 hour is 60 minutes and 1 day is 1440 minutes and 1 month is 43,200. I am developing a document tracking system and would just like to calculate how long a document stayed in a particular office based on the date received and date released.
You can use floor and mod operator.
Floor rounds down a number.
The modulo operator will give you what is left if split evenly.
Example 5%2 = 1
Since 2*2 = 4 and the remaining is 1.
Echo floor(93366/43200) . " months\n";
$rem = 93366%43200;
Echo floor($rem/1440) . " days\n";
$rem = $rem%1440;
Echo floor($rem/60) . " hours\n";
Echo $rem%60 . " minutes";
Output:
2 months
4 days
20 hours
6 minutes
https://3v4l.org/RreDY
I have this function for show timeago from unix timestamp:
function Timesince($original) {
$original = strtotime($original);
// array of time period chunks
$chunks = array(
array(60 * 60 * 24 * 365 , 'year'),
array(60 * 60 * 24 * 30 , 'month'),
array(60 * 60 * 24 * 7, 'week'),
array(60 * 60 * 24 , 'day'),
array(60 * 60 , 'hour'),
array(60 , 'min'),
array(1 , 'sec'),
);
$today = time(); /* Current unix time */
$since = $today - $original;
// $j saves performing the count function each time around the loop
for ($i = 0, $j = count($chunks); $i < $j; $i++) {
$seconds = $chunks[$i][0];
$name = $chunks[$i][1];
// finding the biggest chunk (if the chunk fits, break)
if (($count = floor($since / $seconds)) != 0) {
break;
}
}
$print = ($count == 1) ? '1 '.$name : "$count {$name}s";
if ($i + 1 < $j) {
// now getting the second item
$seconds2 = $chunks[$i + 1][0];
$name2 = $chunks[$i + 1][1];
// add second item if its greater than 0
if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {
$print .= ($count2 == 1) ? ', 1 '.$name2 : " $count2 {$name2}s";
}
}
return $print;
}
This Worked for me. But i need to print timeago only for 3 days, after 3 days need to show normal date like :01/01/2015. in action stackoverflow work with this method.
how do create this ?
step1 : calulate difference
$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date1->diff($date2);
//echo "difference " . $interval->y . " years, " . $interval->m." months, //".$interval->d." days ";
Step 2:
use if condition to show off your date
if($interval->d > 3 || $interval->m >0 || $interval->y >0 ){
// echo out your date in your required format
}
thanks to SO
Use this as an idea and approach....
I am trying to display "{number} {unit-of-time} ago" in my chat. However, when I'm expecting something like "2 minutes ago", I see "45 years" instead.
Nobody has an answer?
Here is the script:
<?php
$con = mysql_connect("localhost", "user", "pword");
mysql_select_db('chat', $con);
$result1 = mysql_query("SELECT * FROM logs ORDER BY id ASC");
$tm = mysql_query("SELECT timestamp FROM logs ORDER BY id ASC");
function _ago($tm, $rcs = 0)
{
$cur_tm = time();
$dif = $cur_tm - $tm;
$pds = array('second', 'minute', 'hour', 'day', 'week', 'month', 'year');
$lngh = array(1, 60, 3600, 86400, 604800, 2630880, 31570560);
for ($v = sizeof($lngh) - 1; ($v >= 0) && (($no = $dif / $lngh[$v]) <= 1); $v--) ;
if ($v < 0) $v = 0;
$_tm = $cur_tm - ($dif % $lngh[$v]);
$no = floor($no);
if ($no <> 1) $pds[$v] .= 's';
$x = sprintf("%d %s ", $no, $pds[$v]);
if (($rcs == 1) && ($v >= 1) && (($cur_tm - $_tm) > 0)) $x .= time_ago($_tm);
return $x;
}
$timeagochat = _ago($tm, $rcs = 0);
while ($extract = mysql_fetch_array($result1)) {
echo "<p class='show_message'><span class='uname'>" . $extract['username'] . "</span> <span class='time'>" . $timeagochat . " </span><br><span class='msg'>" . $extract['msg'] . "</span></p><br>";
}
?>
What can I do to let this function work?
You have to fetch the date:
$tm = mysql_query("SELECT timestamp AS t FROM logs ORDER by id ASC")->fetch_assoc()['t']; //obviously, check the size before you fetch
You probably want to use strtotime() so for instance:
$dif = $cur_tm-strtotime($tm);
The $dif will be in milliseconds.
What are you doing with the loops and the arrays? Too confusing.
5. WHY DO PEOPLE KEEP USING mysql_!!!