Page 1 of 1

Bugged by a session problem

Posted: Wed Mar 28, 2012 5:21 am
by drayarms
I thought I had somewhat of a mastery of sessions, until I encountered this problem. Basically, I'm trying to built a session expired code which is a little bit deviated from your everyday session expired codes. I want the user of a website to be logged out automatically after the session expires, and redirected to the login page. But I also need that, if any other user tried to access that same website without having previously been logged on, he should be redirected not to the login page but the signup page. So basically, the same page (index.php) should redirect the user to login.php if he was logged in and his session expired after 1 minute, or signup.php if he wasn't logged in and tried to access home.php.

So what I tried to do to accomplish this was

- Declare two session variables $_SESSION['id'] = "some value from database" and $_SESSION['logged_in'] = TRUE everytime the user succesfully logs in.

-At the top of index.php, right after session_start(), check to see if 1 minute has elapsed since last activity and if so, unset $_SESSION['logged_in'] without destroying the session. So presumably, all other session variables including $_SESSION['id'] and the session itself remain intact.

-Right below that, check if $_SESSION['id'] is set. If not(meaning the session is not active and hence no user was logged in), redirect to signup.php. If it is set, then check if $_SESSION['logged_in'] is set and if not, redirect to login.php

Now to the code itself

Code: Select all


<?php


//address error handling

ini_set ('display_errors', 1);
error_reporting (E_ALL & ~E_NOTICE);


//Check if max login cookie is set


//Check if max allowable time has elapsed

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 60)) {

    // last request was more than 1 minute ago
 
    unset($_SESSION['logged_in']);     // unset logged_in session variable for the runtime


}

$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp



        //Get the current page url to pass on to the session expired page.
	$url=urlencode("http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);

	
	//Check whether the session variable id is present or not

	if(!isset($_SESSION['id']) || (trim($_SESSION['id']) == '')) {

		 session_destroy();

		 header("location: signup.php");

		exit();

	}else{//If session id is set meaning the session is alive and hasn't been destroyed


		if(!isset($_SESSION['logged_in'])){//If this variable is not set, then session must have expired because this is the variable we unset upon sesssion expire. The session is still alive though and we must destroy it

		//Redirect to login.php and pass on the page url

		$msg = "Your Session Expired Due to Inactivity. Login Below";

		session_destroy();
		

		header("location: login.php?url=$url&msg=$msg");


		}//End of if logged in is not set


	}//End of if session id is set




?>


Well the code works just as i want it to, except for this scenario. If I login with some user's credentials, and open a new page, by typing in url.com in a new window, this new page doesn't redirect to url.com/signup.php but stays on url.com/index.php and all the session variables are available on this new page just like on the old page that was accessed by actually loging in. Well that's expected. The problem is, when the session expires on this page, it gets redirected to url.com/signup.php and not url.com/login.php as expected(note that with the old page that was accessed by actually login in, we do get redirected to url.com/login.php) Now this bothers me because the website is supposed to be redirected to signup.php only if the user started a fresh session without having been logged in as the logic from the code above shows. So, the $_SESSION['id'] variable actually exists(and I actually tested it by echoing it)but yet, the code behaves as if it doesn't with every new page. What could possibly be going on here? I have tried using session_regenerate_id(), but that just keeps the session going without ever expiring. I tried to use the actual session_id()itself in the place of $_SESSION['id'] but in that scenario, the page always gets redirected to url.com/login.php regardless of whether a user was previously logged in or not.


PS: I dont think this has anything to do with the problem but worth noting that the url of a page opened after a user logs in is url.com/index.php but that of a page opened after a user is already logged in is simply url.com

Re: Bugged by a session problem

Posted: Wed Mar 28, 2012 3:43 pm
by phphelpme
I do not understand why this type of function would be required. The user would know whether they have an account or not. So normally the login page is displayed and if the user does not have an account (which they will know if they do or not) then you have a link to register, or allot of sites have the two forms on the same page for login or register new account.

I personally do not see a reason for this function to even exist. Unless I am not seeing something that is critical to your system development. You would have to log the ip addresses of each viewer etc to see if that user has ever logged in before along with the login details or session id used etc as a log. Only then could you redirect the user based on that condition. With you using session nothing is stored on viewers system like cookies so no way of getting that information plus they can be cleared and altered to if need be. IP addresses are mostly dynamic now so this might not even work for allot of the cases too.

Just a little note too regards this line of code:

Code: Select all

header("location: login.php?url=$url&msg=$msg");
if you are using session anyway, then why not pass these variables as session variables and keep your url links clean without any idea of compromise etc.

Best wishes

Re: Bugged by a session problem

Posted: Fri Mar 30, 2012 10:49 pm
by xtiano77
I am not an expert on Sessions either, but this how I would go about enforcing a session timer:

Code: Select all

Class file: Session.php

<?php
class Session {

	public function __construct(){}

	public function createSession(){
		// Create a session timer, the time can be whatever you want
	}

	public function destroySession(){
		// Clears the session data
		// Destroys the session
		// Delete the cookie
	}

	public function checkSessionTimer(){
		// Checks if the session timer and throws an exception upon expiration
		if($_SESSION["SESSION_TIMER"] < time()){
			throw new Exception("Your session expired due to inactivity, please login.");
		}else{
			// Resets the session timer to whatever time you specify
			$_SESSION["SESSION_TIMER"] = time() + 60;
		}
	}

	public function checkValidSession(){
		// You can always add a parameter to the method and specify the target page
		// This will allow you to re-use the same method on all pages you want restrict from
		// visitors without an account and or extablished session.
		try{
			session_start();
			if(!isset(["SESSION_TIMER"])){
				throw new Exception("Unestablished Session, please login.");
			}
			$this -> checkSessionTimer();
		}catch(Exception $e){
			// Process the exception information
			// Redirect to wherever you want
			// Dump the session data unless you have a reason to keep it
			$this -> destroySession();
		}
	}

}
?>

Whatever page: page.php

<?php
require_once "Session.php";

$session = new Session();
// Checks the session timer and redirects to the specified page
$session -> checkValidSession();
// The previous three lines of code can save you a whole lot of typing

// Your code...
?>

Target page: index.php

<?php
// Your target file for expired sessions
?>
Just my two cents, hope it helps.

Re: Bugged by a session problem

Posted: Sun Apr 01, 2012 2:44 am
by social_experiment
@xtiano77 I would incorporate redirects into the class as well; easier to deal with and less "headers already sent" messages