Solved

Sessions - Set and Detect Timeout

Posted on 2008-10-24
15
794 Views
Last Modified: 2009-10-20
Hello Everybody

I have my web application and i need to maintain sessions. I have a problem i dont understand how to do. My application has a search page where the user inserts his criiteria and then the search result is displayed.  Once if the user likes any item in the search result, he cllick and he goes to booking form.

I need to know when the session expires. what if the user clicks the booking button and just stays idle on the booking form for 1 hour without any activity. How can i know that the session is expired.

Im all may pages im using session_start().

The reason Im asking to know that the session is expired is because, once the user likes any item in search result and clicks the book button, i deduct the item from the inventory temporarily and put it in the cart of the user till the payment is complete. Hence for this reason i need to know when the session has expired so that I can put the item back to the inventory. And in my application i want to session to be valid only for 15 mins. How can I do that?

Regards
0
Comment
Question by:VBpassion
  • 6
  • 5
  • 4
15 Comments
 
LVL 82

Expert Comment

by:hielo
ID: 22798052
>>How can i know that the session is expired.
Once the session is expired, the $_SESSION variables are "invalid". So you can use:

if( !isset($_SESSION['username']) || empty($_SESSION['username']) )
{
 header("Location: login.php");//send user to login page
 exit;
}

//if you make it here, then the session is still valid/active
0
 
LVL 82

Expert Comment

by:hielo
ID: 22798054
0
 
LVL 6

Expert Comment

by:fourice
ID: 22798303
You could check and store a timestamp in your session every time a page is called, something like:
// Start session
session_start();

// Check if timestamp session is available and less then 15 min. (=900sec)
$intTimeOut = 900;
if($_SESSION['timestamp'] < 1 || (time() - $_SESSION['timestamp']) > $intTimeOut)
{
// Go to login page or index
}
else
{
// Store/update current timestamp
$_SESSION['timestamp'] = time();
// Rest of the code
}
0
Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

 
LVL 1

Author Comment

by:VBpassion
ID: 22799728
Hi hielo
where shall i write this code, the first line of my page is session_start();
So plz tell me where to write this code and test. shall i write before starting the session or after starting the session.


if( !isset($_SESSION['username']) || empty($_SESSION['username']) )
0
 
LVL 6

Expert Comment

by:fourice
ID: 22800169
You need to write it after starting the session, otherwise there is no session to use. So for the username check you need:
// Start session
session_start();
if( !isset($_SESSION['username']) || empty($_SESSION['username']) )
{
 header("Location: login.php");//send user to login page
 exit;
}
But this not work for your 15 minutes time-out like you wanted.
0
 
LVL 82

Expert Comment

by:hielo
ID: 22800427
>>Hi hielo, where shall i write this code, the first line of my page is session_start();
Immediately after session_start(). You must call session_start() BEFORE you dereference any $_SESSION variable.
0
 
LVL 1

Author Comment

by:VBpassion
ID: 22801776
Hello Friends, it doesn't work. Im stuck in this problem since a week and my project is getting damn delayed, Im now pullig my hairs. Im going crazy.
I did what you adviced, but it doesn't work.

See, can somebody plz give a simple fully working example. so demonstrate session timeout within 1 min with a very simple example so that i can understand. I googled a lot so many people say that same, but no body shows a simple  understanndable answer. I have created a simple page as an example, can somebody help me how to make this work. Now let say below is the index.php

<?php
session_start();
if(count($_post)>0){   # jus to see if th page is posted (self post)
          echo("Hello");
}
<form name="form1" method="post" action="">
  Name:
  <input type="text" name="textfield">
  <input type="submit" name="Submit" value="Submit">
</form>
?>


Now can anybody with the abov example help me how to work with sessions. Lets say if i come to this page and sit idle for 1 min, and then press the submit button, the page shoud tell me sorry session is expired.

thanks a lot for your efforts
0
 
LVL 6

Expert Comment

by:fourice
ID: 22802274
See the code snippet. If you enter the page the first time it stores the timestamp in a session. The first time it's not been longer then 60 seconds, so the form will appear. You can enter a name and hit submit. If you hit the submit within 60 seconds, your name will be shown, if you wait longer then 60 seconds a message will appear saying you have been idle for too long.
I hope is clear enough for you now.

<?php
// Start session
session_start();
 
// Check if timestamp is available
if($_SESSION['timestamp'] == null || $_SESSION['timestamp'] < 1)
{
	// Store current timestamp
	$_SESSION['timestamp'] = time();
}
?>
<html>
	<head>
		<title>No title</title>
	</head>
	<body>
	<?php
	// Check if timestamp session is available and less then 1 min. (=60sec)
	$intTimeOut = 60;
	if((time() - $_SESSION['timestamp']) > $intTimeOut)
	{
		// Idle too long
		echo "You have been idle for more then 1 minute";
		exit;
	}
	else
	{
		if($_POST['textfield'] != "")
		{
			// just to see if th page is posted (self post)
			echo "Name: " . $_POST['textfield'];
		}
		?>
		<form name="form1" method="post" action="">
		  Name:
		  <input type="text" name="textfield">
		  <input type="submit" name="Submit" value="Submit">
		</form>
	<?php
	}
	?>
	</body>
</html>

Open in new window

0
 
LVL 1

Author Comment

by:VBpassion
ID: 22802363
Hi Fourice
Thanks a million, yes it works, but i want to know is this the right way to do and track sessions, im just worried because my project involves financials, it is e-comm website and involves money, so is this method recommended and is it foolproof. Whats is the difference between this example and the one which you were telling me earlier.

plz advice
0
 
LVL 1

Author Comment

by:VBpassion
ID: 22808539
Hi Fourice
I kind of understood code, but what are doing is your are forcefully limiting the life of the user on that pagefor 1 mins. What happens if the user comes on that last few seconds and trys to submit the form and goes to the second page. In my current situation, i have two pages. example abc.php and xyz.php.

ABC.php
<?php
session_start();
// Check if timestamp is available
if($_SESSION['timestamp'] == null || $_SESSION['timestamp'] < 1)
{
      // Store current timestamp
      $_SESSION['timestamp'] = time();
}
$intTimeOut = 60;
      if((time() - $_SESSION['timestamp']) > $intTimeOut)
      {
            // Idle too long
            echo "You have been idle for more then 1 minute";
            exit;
      }
?>
<form action="xyz.php" method="post">
      <input type="submit" name="submit">
</form>


XYZ.php
<?php
 code???

wha should be the code here.
?>



Now, i know your code works well, but what i fail to undersand is, why do we have to compute and make or own ways of doing session. WHAT is php Session is all about, how do other e-comm sites maintain sessions. is itsoo hard to have sessions.

plz help?... i need your help fourice.
0
 
LVL 82

Expert Comment

by:hielo
ID: 22816957
>> What happens if the user comes on that last few seconds and trys to submit the form and goes to the second page
Did you read that out loud? If the session is meant to expire at 10:00am and the request is received at 09:59:59, then it is NOT expired and SHOULD redirect you to the other page. So the implementation shown above would act as expected. But you shouldn't have to do that. You just need to set the appropriate settings before you call session_start():
<?php
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 1);
ini_set('session.gc_maxlifetime', 10);
session_start();
 
if( isset($_POST['Submit']) )
{
	if( !isset($_SESSION['auth']) )
     {
     	echo "expired";
     }
     else
     {
     	echo "session is still good";
     }
}
elseif(!isset($_SESSION['auth']) )
{
	
	$_SESSION['auth']=1;
}
 
if(count($_POST)>0){   # jus to see if th page is posted (self post)
          echo("Hello");
}
?>
<form name="form1" method="post" action="">
  Name: 
  <input type="text" name="textfield">
  <input type="submit" name="Submit" value="Submit">
</form>
<?php
exit;
?>

Open in new window

0
 
LVL 1

Author Comment

by:VBpassion
ID: 22820053
Hello Hielo

Thanks for sharing your comments on my post. I tried your code, but it doesn't work. I even set the gc_max life to 2, and stayed idle for 5 mins. .....but still the session is live.

0
 
LVL 6

Expert Comment

by:fourice
ID: 22820173
Hi VBpassion,
it is possible that ini_set is not allowed on your server. To check this you can use php_info(); to see if it's changed (I believe it says "Local Value" and "Master Value"). Or you can look at the return value (Returns the old value on success, FALSE on failure, see http://www.php.net/ini_set).
As for my code, you asked "WHAT is php Session is all about". My code as well as Hielo's first code both are using php sessions. There are several ways to play with them, with ini_sets or like my code.
Perhaps you can also search for some php session tutorials, just to get more familiar with the concept. Because like you are already mentioning it is important that it works well (especially if you are working with finances).
0
 
LVL 82

Expert Comment

by:hielo
ID: 22828906
>>And in my application i want to session to be valid only for 15 mins
go to your php.ini file and look for:
session.gc_maxlifetime = 1440

change that to :
session.gc_maxlifetime = 900

In case you are wondering:
1440 seconds = (24*60)
24=minutes
60 seconds/minute

Thus, 900=(15*60)

BTW: if you make that change in php.ini, you will NOT have to use:
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 1);
ini_set('session.gc_maxlifetime', 10);

at the start of every page that uses session. You WILL only need to call:
session_start();
0
 
LVL 1

Accepted Solution

by:
VBpassion earned 0 total points
ID: 23132793
Hi the best thing is the capture the current server time frame and set the timer, on every request check the difference, if its greater then destroy and start the session. ele continue browsing
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
This article discusses how to implement server side field validation and display customized error messages to the client.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question