Hello all,

A friend and I are working on a website and we are having some issues with the timeout functionality. We set $_SESSION to the current time at login and then We are using the code below at the top of every page to set the session time every time a page is loaded. It works, except the 'activeTime' is not staying set to the new time when the next page is loaded. So the end effect is that the session expires 10 minutes from when they log-in rather than from the last activity. We have looked all over and can't find why this is happening. Any help would be much appreciated.

session_start();
        //...
        $maxNoActivity = 600; // Seconds of session duration of no activity
	$difference = (time() - $_SESSION['activeTime']);
				
	if($difference > $maxNoActivity)
	{
		session_destroy();
		header("Location: login.php?timeout=1&page=".$_SERVER['PHP_SELF']);
	}
	$_SESSION['activeTime'] = time();
//PUT THIS ON TOP OF YOUR PAGE

//END MY SESSION ON THE SINGLE PAGE
session_start();

if(isset($_SESSION['expiredalready'])=="true"){
    $gointtoifexpired=$_SESSION['returnurlifexpired'];
     echo "<script>alert(\"Session Expired! your previous ordered has been cancelled. Please exit your browser and try again!\")</script>"; die("<script language=\"JavaScript\"><!--
 		 setTimeout(\"location.href = '$gointtoifexpired'\",1000);
				//--></script>");
}

$numberofseconds = 600; //in seconds
set_session($numberofseconds);

function check_session() {
	if (!is_session_valid()) {
		//DO THIS ACTION WHEN SESSION EXPIRED
		$_SESSION['expiredalready']="true";
		$gointtoifexpired=$_SESSION['returnurlifexpired'];
		echo "<script>alert(\"Session Expired! your previous ordered has been cancelled!. Please exit your browser and try again!\")</script>";
		die("<script language=\"JavaScript\"><!--
 		 setTimeout(\"location.href = '$gointtoifexpired'\",1000);
				//--></script>");		//return "close";
	}
	else {
		global $numberofseconds;
		set_session($numberofseconds);
  //      echo $_COOKIE["MYSESSID"];
		return "open";
	}
}

function is_session_valid() {
	if (isset($_COOKIE["MYSESSID"])) {	
    	$SESSION_ID = $_COOKIE["MYSESSID"];	
    	if ($SESSION_ID == session_id()) {
			return true;
		}
	}
	return false;
}

function set_session($expired) { 
	$SESSION_ID = session_id();
	setcookie("MYSESSID",$SESSION_ID,time()+$expired,"/");
}



//HOW TO USE THAT...



        //VERIFY IF SESSION EXPIRED		

        $MobiletmpReturnURL="PUT YOUR URL HERE";
	$_SESSION['returnurlifexpired']=$MobiletmpReturnURL; //constant value of return if session expired		 
	check_session(); //use this everytime you want to check your session is active or not.

Why not just set the session cookie to expire 10 minutes after login. Below is a example of what you would need to place into your login processor:

setcookie(session_name(), $_COOKIE[session_name()], time()+600, '/');

Also note that code needs to go after session_start();

Thank you very much for replying. I don't want to set it to expire 10 minutes after login because our users may be staying on for an extended period of time, but we still want it to expire if they don't do anything for 10 minutes (or whatever time we decide).

rm_Daniweb, I tried what you gave me there, but I'm not sure if all of that is necessary for our page. We have it set up to go back to the login page when it expires. The only issue I'm having is that when I do $_SESSION['activeTime']= time(); from my original posted code, after the page checks if the session has timed out, I have printed $_SESSION and it is indeed that new time that was assigned at that line, but when I reload the page or go to another link $_SESSION is no longer the new time. It goes back to the old time that was assigned to it at login. Is there a reason that this session variable is not holding when I go to another page or refresh the current page?

thank you

If ya want to expire the session 10 minutes after the last page visit then simply place the following code at the top of every page.

<?
session_start();
setcookie(session_name(), $_COOKIE[session_name()], time()+600, '/');

That will make the session last for 10 minutes after visiting the page and unless the user visits another page, the session will expire.

If ya want to expire the session 10 minutes after the last page visit then simply place the following code at the top of every page.

<?
session_start();
setcookie(session_name(), $_COOKIE[session_name()], time()+600, '/');

That will make the session last for 10 minutes after visiting the page and unless the user visits another page, the session will expire.

Whats the maximum session time limit?

Whats the maximum session time limit?

Well time()+600 == 10 minutes. And if that code is placed in each page, it will reset the cookie that holds the session to ten minutes from the current time.

Thank you very much for the suggestion. We decided not to use that solution because of the rare case when someone has cookies disabled. We were able to make it work the way I had it written. Our problem was that we were passing SESSION to a function (secure) right before we checked it as you can see above because we didn't fully grasp the term "super global." This was causing issues but now that we don't pass SESSION and we just use it where it's needed it works just fine. Thank you again for the replies.

We decided not to use that solution because of the rare case when someone has cookies disabled.

Just a note on that. Sessions do use cookies. For a session to know which computer the session applies to, the session must either send a cookie to the client as proof of identity or have that identity code in the url. So in most cases it doesn't matter if the user doesn't have cookies enabled since without cookies there ain't sessions unless identity is sent via url.

Just a note on that. Sessions do use cookies. For a session to know which computer the session applies to, the session must either send a cookie to the client as proof of identity or have that identity code in the url. So in most cases it doesn't matter if the user doesn't have cookies enabled since without cookies there ain't sessions unless identity is sent via url.

I'm not sure that this is correct. Sessions and cookies are similar, but cookies are stored on the client whereas session data is stored on the server. If the client has cookies disabled, you can't use setcookie etc, but you can use session data. Sessions do not have to use cookies, they are separate but can interact with each other like any data. You do not need to use cookies, they can be handy to store data client side but are not necessary for many situations.

Well try checking your cookies for a cookie from one of your sites and I think the cookie by default is called PHPSESSID. If find that cookie while browsing your website that is using sessions then that is living proof that sessions usually use a single cookie for identity.

Hi
Would it not be easier to just use the following in your meta tags on each page?

<meta http-equiv="Refresh" content="300; url=http://www.site.com/logout_page.php" />

The only problem with that code is that some browsers do not always have the meta tags enabled. That is why it is by far better to use php and not html in this case. And the following code placed in each page will work the same way sessions work if the session id is not in the url:

<?
session_start();
setcookie(session_name(), $_COOKIE[session_name()], time()+600, '/');

If you do not place the session id in the url it will have no influence on the sessions reliance of cookies. That can easily be tested and prooved as mentioned earlier.
-_-

But what if cookies are disabled?
Wouldnt that create the same problem.

Then again, you can test if cookies are on and tell the user to put them on in order to access something. Whereas true, meta can be blocked.

But what if cookies are disabled?
Wouldnt that create the same problem.

Then again, you can test if cookies are on and tell the user to put them on in order to access something. Whereas true, meta can be blocked.

Well if cookies are disabled, weather you use my code or not sessions will be blocked. That is why in the past there have been so many topics about sessions not working. Because unless you place the session id in the url which nobody does, there is no way for the server to know the computers identity. In other words, sessions use cookies to know which sessions go to which client computers. And to test this situation you need to both disable cookies and empty cookies so there are no active sessions available. I wish this was made clear to new php programmers.

Il be honest, I had no idea.
When you say

In other words, sessions use cookies to know which sessions go to which client computers.

I did wonder a while. There are sessions coming in from loads of websites, surely there must be loads with the same names, so then how does the server figure out which is intended for each website. But what you said clears this up. Thanks for the info.

so then how does the server figure out which is intended for each website

You will find that with the design of the cookies system in general, every cookie in existance is set to serve one domain only. And of course, there is only one defined session per domain. So that is how the browser separates the cookies for the intended website.

Thanks for pointing that out. It bugged me a while back but I guess i forget to do some research.

Happy easter :)

This article has been dead for over six months. Start a new discussion instead.