PHP Session timeout, problem with code - php

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) { ... }

Related

php continue execution after leaving the page

I have a simple script that counts from 1 to 5000 with a for loop. It flushes output in real time to browser and shows a progress bar with %.
What I have: If I leave the page, the process interrupts. If I come back, it starts from 0.
What I want to achieve: If I leave the page, the process continues and, If I come back , it shows the right percentage.
Example: I run the process, it counts till 54, I leave the page for 10 seconds, when I come back it shows me 140 and continues to flush.
Is it possible?
I would suggest you to use server workers - scripts which are intended to run independently from webserver context.
The most common way of doing it - usage of message queues (RabbitMQ, Qless, etc). Event should be initiated by the script in web context, but the actual task should be executed by queue listener in a different context.
What you have asked seems quite simple to do with a session. (Purely assuming on the use case given). This is not running any process in the background, it just simply keep track of the time and show the progress. That's why I said "based on what you asked". If you want to keep track of any real background tasks, then I believe the case would be totally different, and you will have to change the wordings of your question as well ;)
Something like this would do.
<?php
session_start();
$s = &$_SESSION;
$sleep = 1; //seconds
//check if we have a value set in session before, if not set default = 0.
if(!isset($s['last'])){
$s['last'] = 0;
}
//check if we have a last time set in session before. if not set a default = curret time.
if(!isset($s['time'])){
$s['time'] = time();
}
//get the idle time of the user.
$idle = time() - $s['time'];
//start the loop..and set starting point.
$start = $s['last'] + ($idle / $sleep);
for( $i = $start; $i < 100; $i++){
echo $i . '<br />';
$s['last']++;
$s['time'] = time();
flush();
sleep($sleep);
}
Hope it helps!!

How do I stop the timeout of sessions and make session time infinite? (PHP)

I'm using OpenID (LightOpenID) with PHP and I can't help but notice that the session times out after a very short period of time, and it is a problem. How can I increase the session time to infinite? I've googled many methods but I don't believe I am adding the code in the correct places. If it's necessary for me to paste my code, just say so, but I didn't think it was needed. All help is greatly appreciated! :)
`
<?php
if(!isset($_SESSION["timeout"])){
$_SESSION['timeout'] = time();
};
$st = $_SESSION['timeout'] + 120; //session time is 2 minutes, Changing this value can help you.
if(time() < $st){
echo 'Session will last 2 minutes';
}
?>`

PHP Check if a user is online

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";

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']);
}

If statement, sessions variables

The following code is within an ajax call. I'm trying to make sure people don't vote on questions with a certain id too often using sessions.
So they click a button, which executes the following php code:
$id=$_GET["id"];
if ((isset($_SESSION["$id"]) && ((time() - $_SESSION["$id"]) > 180)) || (!isset($_SESSION["$id"]))) {
// last vote was more than 3 minutes ago
$_SESSION["$id"] = time(); // update/create vote time stamp
//there is code here to add the vote to the database
}
else{
echo "sorry, you've already voted recently";
}
So I'm creating a session variable for each question id which holds the time() of their last vote. I would do this with cookies, but they can be disabled.
Currently, there is a bug somewhere with my logic, because it allows the user to keep clicking the button and adding as many votes as they want.
Can anyone see an error that I have made?
using sessions to prevent multiple voting makes very little sense.
sessions do use cookies with the same drawbacks
unlike strings, variables in PHP should be addressed without quotes. such a false usage WILL cause an error someday.
I see no point in checking for isset($_SESSION[$id]) twice.
There was a bug in PHP which disallowed numerical indices for the $_SESSION array. Dunno if it was corrected nowadays.
As it was pointed out by Sajid, you have to call session_start() before using $_SESSION array.
now to the logic.
to me, it seems the code won't let anyone to vote at all. as it won't pass isset($_SESSION[$id]) condition for the first time and won't let $_SESSION[$id] to be set and so on.
it seems correct condition would be
if ( (!isset($_SESSION['vote'][$id]) OR (time() - $_SESSION['vote'][$id]) > 180) )
You need to call session_start() to start the session before any headers are sent. Otherwise, sessions will not be enabled unless the ini setting to autostart sessions is on. Also, your server must be correctly configured to be able to store session files (usually a writable tmp dir is needed). See more about sessions here: http://www.php.net/manual/en/ref.session.php
There might be a problem with the if statement. Try the following
$id=$_GET["id"];
if (((isset($_SESSION[$id]) && ((time() - $_SESSION[$id]) > 180))) || (!isset($_SESSION[$id]))) {
// last vote was more than 3 minutes ago
$_SESSION[$id] = time(); // update/create vote time stamp
//there is code here to add the vote to the database
}
else{
echo "sorry, you've already voted recently";
}
Perhaps time() returns milliseconds and you should compare to 180000 instead of 180.

Categories