Jump to content
xisto Community
Vyoma

User Authentication Session Handling Problems Authorization server variables not staying across pages

Recommended Posts

This is quite a bit of problem I am facing, and I cannot point exactly where I am going wrong. I have been lurking around here at the Asta Host forums with regard to login and user authentication scripts and I have got as far as this:

 

- Starting a session

- Registering a session variable

- Using the variable to check if the user is authenticated or not.

- Authenticating the user through MySQL database

- Logging of the user, by setting the session variable to un-authenticated

 

I have been able to achive the following things too that I think is not related to this problem:

- Encapsulate the database handling to a seperate source file

- Use a templating system of my own.

- Handle everything in only one page using the querying through URL (this is my requirement due to the templating system I use) - I want only one file (index.php) to be called with appropriate action requests (?q=login or ?q=logout)

 

Here is the code I have so far:

<?phpsession_start();session_register('auth');require_once('database.inc');// These $d_<something> variables will be placed in the template$d_html_head = 'Some portal DART';$d_header = 'The header - DART';$d_status = NULL;$d_content = NULL;$d_nav = '<h2>Link set 1</h2><ul><li><a href="#">Link 1</a></li><li><a href="#">Link 2</a></li><li><a href="#">Link 3</a></li></ul><h2>Link set 2</h2><ul><li><a href="#">Link 4</a></li><li><a href="#">Link 5</a></li><li><a href="#">Link 6</a></li></ul><h2>Link set 3</h2><ul><li><a href="#">Link 7</a></li><li><a href="#">Link 8</a></li><li><a href="#">Link 9</a></li></ul>';$d_footer = 'copyright info';$q = '';// Database handling part$dartdb = new dbhandler;$connection = $dartdb->setconnection( 'dbadmin', 'dbpassword', 'localhost');if(!$connection)  $d_status .= "Unable to get a connection <BR /> $dartdb->errorstring <BR />";$connection = $dartdb->setdatabase('dartdb');if(!$connection)  $d_status .= "Unable to select DART database <BR /> $dartdb->errorstring <BR />";if ( isset($_GET['q']) )  $q = $_GET['q']; if ( $q == 'login')  {  // Check the 'user' and 'pass' against database and set    // 'auth' based on the result  $loginmessage = "The Employee number or the password given is wrong.  Please try again.";  $_SERVER['auth'] = 'NO';    $user = NULL;  $pass = NULL;    $user = $_POST['user'];  $pass = $_POST['pass'];      $query = "SELECT * FROM dart_emp WHERE empid = '".$user."'";  $dartdb->query($query);  if ( $user != NULL && $dartdb->result != NULL )	{	$array = $dartdb->fetch_object();	if( isset($array->empid) 		&& $array->empid == $user 		&& $array->password == $pass )	  {	  $loginmessage = "Login successful.";	  $_SERVER['auth'] = 'YES';	  }	}  $d_status .= $loginmessage;  }else if ($q == 'logout')  {  // User has logged out. Hence set the 'auth' to 'NO'  $_SERVER['auth'] = 'NO';  $d_status .= 'Logged out. <BR />';  }if( isset($_SERVER['auth']) && $_SERVER['auth'] == 'YES' )  {  $d_status .= 'Authorized access <BR />';  $d_content .= 'Content, content. <BR />Logout <A href="?q=logout">link</A>.';  }else  {  //Show the login form  if ($q != 'logout')	$d_status .= 'Not logged in. <BR />';  $d_content .= '<form action="?q=login" method="post" name="login">  Employee Number: <input type="text" name="user" size="6" maxlength="6" id="user" /> <BR />  Password: <input type="password" name="pass" size="30" maxlength="30" id="pass" /> <BR />  <input type="submit" name="login" value="Login" id="login" />  </form>';  }// This is the templating system I use.  The above $d_<something> values// are replaced in the appropriate placesrequire 'template/page.tpl';?>

Now, here is my problem. Once I log in, the URL will be:

LOCALHOST/index.php?=login

 

After successful login, it will show the content.

Now, if I type the http://forums.xisto.com/no_longer_exists/, it should still be showing the content. But it does not. For some reason, I am loosing the $_SERVER['auth'] variable. I am not sure, where in the flow I am doing wrong.

 

Could some one please check this up and let me know what I am doing wrong, or what more should I be including?

 

Please let me know, if you need anything more, or want me to explain why I put the code as I put it there.

Share this post


Link to post
Share on other sites

I didn't get into to your script very much, but isn't it $_SESSION['auth']; you want to use and not $_SERVER; superglobal?I myself that to optimize the script, usually at the start of the script, where I need to use superglobals, I do something like this $s =& $_SERVER; to use $s as superglobal, very convenient, but I don't do this for SESSION and COOKIES as I had problems. :unsure:

Edited by Quatrux (see edit history)

Share this post


Link to post
Share on other sites

Oh! The _SERVER and _SESSION variables are different. I should have thought about that. I will check this up and let you guys know how it turns out to be.

Share this post


Link to post
Share on other sites

Here's an example of my login which seems to work just perfectly thus far:

I do use files split up though.

What I do with login.php is display a form with two input text fields and send that to my check_login.php file which checks the information against the database and then registers the session like so:

session_register('username');$_SESSION['username'] = $username;session_register('password');$_SESSION['password'] = $password;

$username and $password being the variabels send from the form that were validated to be correct. If not I just sent them back the login.php?error=incorrectlogindetails or somesuch.

For pages that need to check if a user is logged in:

session_start();if(isset($_SESSION['username']) && isset($_SESSION['password'])){header("location:login_successful.php?error=loggedin");}

Which is in my login.php file, if isset is true then they are allready logged in and do not need to be here so it redirects them.

And for logging out, it's as simple as:

session_start();session_destroy();

I'm not sure if it's the best way to do it but it hasn't failed me yet.

Share this post


Link to post
Share on other sites

I wonder why people here still is using session_register(); Here is a caution "If you are using $_SESSION (or $HTTP_SESSION_VARS), do not use session_register(), session_is_registered(), and session_unregister()." :unsure: and to end the session, one of the best method is to do this:

function session_delete($sname = 'Current User') {	# Set Session Name to a Variable	$name = session_name();	/* Empty the Cookie from Session */	if (!headers_sent() ) { setcookie($name,"",0,"/"); }	/* Remove the Cookie Value */	unset($_COOKIE[$name]);	/* Remove all the Info from the Super Global */	$_SESSION = array();	/* Free all session variables */	session_unset();	/* Destroy all data registered to a session */	if (session_destroy() === FALSE) {		return FALSE;	} else {		return TRUE;	}	}

and just call the function when you need to logout or remove the session. :D

Share this post


Link to post
Share on other sites

What's wrong with session_register()? It works and is the only thing that worked for me back when I first wrote it lol.

 


Well, read the PHP Manual and search google on session register, it isn't needed anymore.

 

Caution

 

If you want your script to work regardless of register_globals, you need to instead use the $_SESSION array as $_SESSION entries are automatically registered. If your script uses session_register(), it will not work in environments where the PHP directive register_globals is disabled.

 


register_globals: important note: Since PHP 4.2.0, the default value for the PHP directive register_globals is off, and it is completely removed as of PHP 6.0.0. The PHP community encourages all to not rely on this directive but instead use other means, such as the superglobals.

 


Look at this code and read the comments.

 

<?php// Use of session_register() is deprecated$barney = "A big purple dinosaur.";session_register("barney");// Use of $_SESSION is preferred, as of PHP 4.1.0$_SESSION["zim"] = "An invader from another planet.";// The old way was to use $HTTP_SESSION_VARS$HTTP_SESSION_VARS["spongebob"] = "He's got square pants.";?>

session_register() is deprecated !!!

Share this post


Link to post
Share on other sites

Ok. As for the problem I had, it got solved when I replaced all _SERVER occurances with _SESSION. But I see that this thread has developed quite a bit since I last left. Yes, I have heard that session_register is deprecated. So, Quatrax, should I just go ahead and use _SESSION variables and not do any session_open() and session_register() functions?

Share this post


Link to post
Share on other sites

Yes. if you use Xisto free hosting service on this free hosting server, you don't need to use these functions, just set the superglobal variable $_SESSION; and thats all, everything is on the PHP Manual, when PHP6 comes, it will be the best/easiest scripting/programming language, most of the problems will be removed, but most of the servers will still run on php4 so you all "must" write the code to work on all php4 php5 and php6 and even php3 if you have time.I recommend to go through the php manual user comments not in a day but time with time, when you write something big, to look up the manual and check the function you use what can it do and how to use it and with time you'll be a pro. :unsure:

Share this post


Link to post
Share on other sites

Well for now (for me) it's basically what ever works works, when I am happy with features and functioning I'll go through the whole lot and remove redundant code and fix things up.

Share this post


Link to post
Share on other sites

Actually whenever you want to use (or read) session variables you must always start a session using session_start() the you can

echo $_SESSION['myvariable'];
You must use session_start() to assign or use $_SESSION variables. It is a good practice to place the session start at or very near the beginning of your script to avoid the error about resending headers.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.