Solved

Sessions - Set and Detect Timeout

Posted on 2008-10-24
15
789 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
 
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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

757 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now