note 19190 added to ref.session

From: Date: Tue, 19 Feb 2002 12:18:14 +0000
Subject: note 19190 added to ref.session
Groups: php.notes 
Request: Send a blank email to php-notes+get-26786@lists.php.net to get a copy of this message
If you are running PHP with register_globals = on, and you ain't able to turn it of, either beacuse you are not allowed to change this setting or because of backwards-compatibility reasons, secure session handling is somewhat complicated. I wrote this class as a workaround to deliver secure, realtime sessionhandling under that circumstances: <?php class mySession { var $s_vars = array(); //start session with name $name function mySession($name) { session_name($name); session_start(); //determine session variables foreach($GLOBALS["HTTP_SESSION_VARS"] as $key => $value) $this->s_vars[substr($key,10)] = $value; } //register session variable function setSessionVar($key, $value) { if(!session_is_registered("mySession_".$key)) session_register("mySession_".$key); $GLOBALS["mySession_".$key] = $value; $this->s_vars[$key] = $value; } //return session variable function getSessionVar($key) { return $this->s_vars[$key]; } //initialize session function initSession($name, $pass) { //if input is complete, check if user exists in database if($name && $pass) { /*include a database login here if needed*/ //querystring. change it to match your requirements... $qst = sprintf("SELECT * FROM user WHERE login='%s' AND pw='%s'", addslashes(strtolower($name)), addslashes($pass)); $res = mysql_query($qst) or die(mysql_error()); //if user is found, register some variables. if(mysql_num_rows($res) > 0) { $row = mysql_fetch_array($res); //authentification $this->setSessionVar("login", true); //you can register what ever you want... $this->setSessionVar("var1", $row["value1"]); $this->setSessionVar("var2", $row["value2"]); } } } //kill session function killSession() { session_destroy(); $this->s_vars = array(); } } ?> To use this class, simply create a new object $login = new mySession("name"); instead of calling session_start(); Now you can register new variables, and change their values at any time using $login->setSessionVar("name"). You can get the value of any variable registered before using $login->getSessionVar("name). E.g. if you want to confirm whether the user is logged in: if($login->getSessionVar("login")) { code }. That should make the usage of sessions under register_globals a little more worry-free :) Comments? Send a mail! Tim -- http://www.php.net/manual/en/ref.session.php http://master.php.net/manage/user-notes.php?action=edit+19190 http://master.php.net/manage/user-notes.php?action=delete+19190 http://master.php.net/manage/user-notes.php?action=reject+19190

« previous php.notes (#26786) next »