PHP Check if a user is online - php

Could anyone tell me why this doesn't work? In my database lastactive is 2013-12-10 16:15:12, updates every time a user refreshes any page on my website.
I select it and set it as a variable:
$lastactive = $row[5];
Here's where I thought it should work, but doesn't. Using 10 seconds for testing.
if(time() > $lastactive+10){
print('<div id="user_online_status" style="color: #aaa;">[OFFLINE]</div>');
}
else if(time() < $lastactive+10){
print('<div id="user_online_status">[ONLINE]</div>');
}

You're comparing a unix timestamp to a MySQL datetime string. You need to convert it to a unix timestamp before comparing the two:
$lastactive = strtotime($row[5]);

Replace your SELECT statement from:
SELECT lastOnline FROM user
to something like...
SELECT UNIX_TIMESTAMP(lastOnline) FROM user
that's it. You're currently checking the Date string against a UNIX Timestamp.

I dont see its good idea to check for time.
What if user doesnt refresh the page , he let the page open and went to eat ? . he will be loggedout? it will be anonying.
I guess better is to use unload
$(window).unload(function() {
// Send an Ajax request to logout.php
});

if user doesnt refresh the page, you can check it on server using cron.
$limit = $userOnline+60; // cron set to run every minute
if($userOnline < $limit)
$userStatus = "offline";
else
$userStatus = "online";

Related

MSQLi query doesn't delete data at specific time

I want to delete data from table at specific time. For example at 15:00.
My code looks like this:
$time = date("H:i");
$timeToDel = date('H:i', strtotime("15:00"));
if($time == $timeToDel) {
mysqli_query($conn,"DELETE FROM table1");
mysqli_query($conn,"DELETE FROM table2");
}
There is that, when i open the page at 15:00, data from database will be deleted, but when I open the page at 15:01, data won't be deleted from database and they will be still visible on page.
Whole script is on hosting and not on my localhost.
Mostly server time is different from local time , So check server time and it's format.
You have to use cron job,Using cron job you can execute file with a specific time. you can learn it from here https://www.siteground.com/tutorials/cpanel/cron-jobs/.

comparing if time is greater than zero

i have a code that i want to execute if time is greater than zero.i have tried almost all the solutions from stackoverflow but did not get my desired result.
i have tried so far
$query="select TIMEDIFF(date_and_time,NOW()) as time_remaining from exam_schedule";//query to get remaining time from database
if($remaining_time>0)
//run script
else
redirect to another page
if((int)$remaing_time>0)
//run script
else
redirect to another page
if($remaing_time>strtotime('00:00:00'))
//run script
else
redirect to another page
if($remaing_time>mktime(0,0,0))
//run script
else
redirect to another page
i am getting $remaing_time from database . its the difference b/w (current and stored time) i.e stored_time=10:30 ,current_time 10:20, remaining_time=00:00:10
Use TIME_TO_SEC to turn an HH:MM:SS string into seconds.
SELECT TIME_TO_SEC(TIMEDIFF(date_and_time,NOW())) AS time_remaining FROM exam_schedule
Then do
if ($remaining_time > 0)
All i need was
$remaining_time > "00:00:00"
because $remaining_time is a string type variable.

How to prevent users to open same page more than once at a time

On my website people earn points by seeing a page. They get 1 point for each second they keep the page open (the page keeps rotating Advertisements).
Some people have started exploiting this by opening that page multiple times all together and hence are earning more points! for example if the user open the page 10 times then he is earning 10 points for each second. I don't want them to earn more than 1 point per second.
How can I prevent the users from opening that page more than once at the same time?
Thanks in advance.
note : My website is php based.
I have on easy but not reliable way in mind:
Set a Sessionvar like
$_SESSION['user_already_on_page'] = true;
Now you can check for this variable and return an error page or something like that.
if($_SESSION['user_already_on_page'])
{
//maybe the user has left unexpected. to workaround this we have to check
//for the last db entry. Examplecode:
$query = mysql_query($_db,'SELECT LastUpdated FROM Pointstable WHERE U_Id = $uid');
$row = mysql_fetch_array($query);
if((time()-$row['LastUpdated']) < 5)
{
die("You are already on this page!");
}
//$_SESSION['user_already_on_page'] is set but the last update is older than 5 sec
//it seems, that he unexpectedly lost connection or something like that.
}
To unset this variable you could fire an AJAX-Script on pageclose that unsets this variable.
So your unsetonpage.ajax.php could look like this:
<?php $_SESSION['user_already_on_page'] = false;?>
And your JS-Part (using jquery):
$(window).bind('beforeunload', function(eventObject) {
$.ajax({url:'./ajax/unsetonpage.ajax.php',type:'GET'});
});
This should work.
Add the time when the page is opened to the database. Whenever the page is opened check if the difference b/w that time and current time is less than xx seconds then redirect the user. If the difference is more than xx seconds then update that time.
//--- You make session in startup called (my_form)
if (!empty($_SESSION['my_form']))
{
if ($_SESSION['my_form']== basename($_SERVER['PHP_SELF']))
{
header("Location:index.php");
exit();
} else {
$_SESSION['my_form']= basename($_SERVER['PHP_SELF']);
}
} else {
$_SESSION['my_form']= basename($_SERVER['PHP_SELF']);
}

Expire unix or time() code after x hours

I am trying to create a forgot password feature which will expire the link created after x hours. So I am storing time() data in database value when a user requests a password reset. So how can I expire it?
three options:
compare the time you saved on the db with the one you get when the user click the link
Use a cron job and make it run periodically
Just don't save in the db and make the link to care about everything. You could use a signature + a salt to avoid users to modify this link
like:
$now = time();
$sk = sh1($user_id . $now . "yoursupersalthere")
$link = "http://www.example.com/forgot.php?id={$user_id}&ts={$now}&sk={$sk}"
that will be the link you sent to the user. Then to make the check
$ts = $_GET['ts'];
$user = $_GET['id'];
$sk = $_GET['sk'];
if (!$sk == sh1($user_id . $now . "yoursupersalthere")) {
die("bad signature");
}
elseif (time() - $ts > 3600 /* or put your expiration limit */) {
die('link expired');
}
// do your job
You're probably having a table entry with a reset link, just add a date field to it, and then either include a WHERE expiredate<NOW() or clean the table from time to time with a simple DELETE from table WHERE expiredata<NOW().
One method of doing this is to check to see if the link is expired when the link is clicked -- some pseudo-code:
// when the link is clicked pull the information from the database and get the time
// SQL goes here
// this will give you the difference in seconds
$diff = time() - $timestamp_from_db;
// we'll pretend the time expires in 8 hours
$expires_in = 8 * 60 * 60;
// for this example we'll pretend the expiration is 8 hours
if($diff <= $expires_in)
{
// has not been more then 8 hours
}
else
{
// has been more then 8 hours
}
The best way to do this that keeps the table clean is to implement the following:
The table needs at least the account ID with a UNIQUE index and foreign key to the accounts table, the hash with a UNIQUE index and a timestamp.
In the page that creates the link, do not allow "reset my password" based on information that can be obtained by a random person. If you do this, one can fill your table with reset password requests and generate spam and security concerns with your users.
In the page where the link is verified first delete all expired records by comparing NOW() with the stored timestamp, then simply SELECT using WHERE='$hash' (of course, you sanitize $hash). Given the UNIQUE index on the hash, this can only return one row or no rows.
The UNIQUE index on the account ID ensures that people cannot request multiple resets within the expiration time.

PHP Session timeout, problem with code

I have some code that will log the user out after x seconds of inactivity. The problem is that it logs them out before the time specified it doesn't even count the inactivity.
This is the code:
<?php
$_SESSION['loginTime'] = time();
if($_SESSION['loginTime'] < time()+10*60){
$error_msg ="Logged out due to inactivity";
showLoginPasswordProtect($error_msg);
session_destroy();
}
?
Well $_SESSION['loginTime'] is the timestamp that they logged in (hopefully) which will always be less than the current timestamp, because you add one for every second. So you need to do this:
<?php
if($_SESSION['loginTime'] + 600 < time()){
$error_msg ="Logged out due to inactivity";
showLoginPasswordProtect($error_msg);
session_destroy();
}
?>
This way it will run the statement if 600 seconds have passed.
Look at what your script is doing:
$_SESSION['loginTime'] = time();
... sets the 'loginTime' to the current time. Let's say the current time is '10'
if($_SESSION['loginTime'] < time()+10*60)
... since we're assuming the current time is 10, then time()+10*60 becomes 10+10*60 = 610, and the if() becomes: if (10 < 610) {
So, your code will ALWAYS log out the user, since your logic is broken.
You need to set the loginTime ONCE, in the login script, instead of setting it each time, as you are now.
You need to set $_SESSION['loginTime'] in a separate script, presumably after the user is authenticated.
Then in this script you need to figure out the difference between the session time and the current time, and then see if it is larger than your timeout threshold.
For example:
if( (time() - $_SESSION['loginTime'] ) > 10*60) { ... }

Categories