Martin J
Martin J

Reputation: 15

How can I echo if a user is online or offline?

I found a code that transform a timestamp from when a user last logged in. It really short but works just fine displaying x seconds, 2 days, etc.

The problem is that i wish to transform the first x minutes (max 5min) to say <div class="green">ONLINE</div>

heres the php:

<?php
function humanTiming ($time)
        {

            $time = time() - $time; // to get the time since that moment
            $time = ($time<1)? 1 : $time;
            $tokens = array (
                31536000 => 'year',
                2592000 => 'month',
                604800 => 'week',
                86400 => 'day',
                3600 => 'hour',
                60 => 'minute',
                1 => 'second'

                // Tried to replace seconds with <div class="green">ONLINE</div>
                // but will end up looking like x ONLINEs where x = seconds
            );

            foreach ($tokens as $unit => $text) {
                if ($time < $unit) continue;
                $numberOfUnits = floor($time / $unit);
                return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
            }

        }

echo humanTiming( strtotime($user_last_life) );
?>

Followup question : What is the most secure and best way to update a database with timestamp? I have problems having it update after login but have added this code in my head.php

$updated_life_id = htmlentities($_SESSION['user']['id'], ENT_QUOTES, 'UTF-8');
$set_last_life = "UPDATE users SET last_life = time() WHERE id = '$updated_life_id'";
$datab->query($set_last_life);

Upvotes: 0

Views: 76

Answers (1)

Hanky Panky
Hanky Panky

Reputation: 46900

if(strtotime($user_last_life) >= time()-300)   // 300 seconds = 5 minutes
{
  echo '<div class="green">ONLINE</div>';
}

And for your database question

How can I prevent SQL injection in PHP?

Upvotes: 1

Related Questions