To Kill a session

I have found a session example in a PHP site and modified it a little bit, It works great but I dont know how to log the person out, Im very new to sessions. Here are the login and session files

login.php
[php]

<?php session_start(); require_once './include/session.php'; $ss = new SecureSession(); $ss->check_browser = true; $ss->check_ip_blocks = 2; $ss->secure_word = *****; $ss->regenerate_id = true; include './include/mysql.php'; mysql_connect("$host", "$user", "$pass") or die(mysql_error()); mysql_select_db("$database") or die(mysql_error()); if ($ss->Check() || isset($_SESSION['logged_in']) || $_SESSION['logged_in']) { header("Location: members.php"); die; } //if the login form is submitted if (isset($_POST['submit'])) { if(!$_POST['pass'] & !$_POST['username']) { die('You must enter a valid Username and Password'); } if(!$_POST['username']) { die('You must enter a valid Username'); } if(!$_POST['pass']) { die('You must enter a valid Password'); } $check = mysql_query("SELECT * FROM USERS WHERE NAME = '".$_POST['username']."'")or die(mysql_error()); $check2 = mysql_num_rows($check); if ($check2 == 0) { die('That user does not exist in our database. Click Here to Register'); } while($info = mysql_fetch_array( $check )) { $_POST['pass'] = stripslashes($_POST['pass']); $info['PASSWORD'] = stripslashes($info['PASSWORD']); $_POST['pass'] = md5($_POST['pass']); if ($_POST['pass'] != $info['PASSWORD']) { echo "Recorded MD5 password is................"; echo $info['PASSWORD']; ?>
<?php echo "Entered MD5 Converted Password is."; echo ($_POST['pass']); ?>
<?php die('Incorrect password, please try again.'); } else { $ss = new SecureSession(); $ss->check_browser = true; $ss->check_ip_blocks = 2; $ss->secure_word = $_SERVER['REMOTE_ADDR']; $ss->regenerate_id = true; $ss->Open(); $_SESSION['logged_in'] = true; header("Location: members.php"); die(); } } } else { // if they are not logged in ?>

Login

Username:
Password:
<?php } ?> [/php]

session.php
[php]

<?php class SecureSession { // Include browser name in fingerprint? var $check_browser = true; // How many numbers from IP use in fingerprint? var $check_ip_blocks = 0; // Control word - any word you want. var $secure_word = '*****'; // Regenerate session ID to prevent fixation attacks? var $regenerate_id = true; // Call this when init session. function Open() { $_SESSION['ss_fprint'] = $this->_Fingerprint(); $this->_RegenerateId(); } // Call this to check session. function Check() { $this->_RegenerateId(); return (isset($_SESSION['ss_fprint']) && $_SESSION['ss_fprint'] == $this->_Fingerprint()); } // Internal function. Returns MD5 from fingerprint. function _Fingerprint() { $fingerprint = $this->secure_word; if ($this->check_browser) { $fingerprint .= $_SERVER['HTTP_USER_AGENT']; } if ($this->check_ip_blocks) { $num_blocks = abs(intval($this->check_ip_blocks)); if ($num_blocks > 4) { $num_blocks = 4; } $blocks = explode('.', $_SERVER['REMOTE_ADDR']); for ($i=0; $i<$num_blocks; $i++) { $fingerprint .= $blocks[$i] . '.'; } } return md5($fingerprint); } // Internal function. Regenerates session ID if possible. function _RegenerateId() { if ($this->regenerate_id && function_exists('session_regenerate_id')) { session_regenerate_id(); } } } class DestroySession { function Open() { session_destroy(); die; } } ?>

[/php]

i understood it that way that u wanna have a logout link, is that right?

make a link:

<a href="login.php?logout=logout">log out</a>

and use session_destroy(); i login.php
[php]if(isset($_GET[‘logout’]))
{
session_destroy();
header(“Location: http://www.urdomain.de”);
}[/php]

Leaves a few errors but I can figure them out easily. Thanks for your help, I just had the destroy in the wrong place not to mention file :)

Its working great, Thanks. One more issue to resolve if anyone is up to it. Say from the session above, is it possible to print to screen the user name they are logged in under? Thanks
Draco

This should be fairly simple. Just when pulling the information from the database store the username and then you can echo it out on all pages.

Is there a simpler way to store it rather than post/get? Thanks

Sorry, I meant to say you can just store it in a Session Variable.

If you are going to have a generic message with the users name in it, I would store the whole message. For example,

$msg = "Welcome " . $username . “, hope you enjoy the site!”;

$_SESSION[‘welcome_msg’] = $msg;

Then you can just pass this session variable to each page you will need it on.

$welcome_msg = $_SESSION[‘welcome_msg’];

You can just echo out the variable. This way if the message ever changes you don’t need to change in many different spots. Just change it on the first page it gets set.

Thanks! Ill go play with that a bit :)

Your method works great, I just cant figure out how to get the user name they are logged in as into the session variable. I think I should be able to send it from the login script to the session script, I just dont know how. Here is the login script

login.php
[php]

<?php session_start(); require_once './include/session.php'; $ss = new SecureSession(); $ss->check_browser = true; $ss->check_ip_blocks = 2; $ss->secure_word = $_SERVER['REMOTE_ADDR']; $ss->regenerate_id = true; include './include/mysql.php'; mysql_connect("$host", "$user", "$pass") or die(mysql_error()); mysql_select_db("$database") or die(mysql_error()); if(isset($_GET['logout'])) { session_destroy(); header("Location: ./login.php"); die; } if ($ss->Check() || isset($_SESSION['logged_in']) || $_SESSION['logged_in']) { header("Location: members.php"); die; } if (isset($_POST['submit'])) { if(!$_POST['pass'] & !$_POST['username']) { die('You must enter a valid Username and Password'); } if(!$_POST['username']) { die('You must enter a valid Username'); } if(!$_POST['pass']) { die('You must enter a valid Password'); } $check = mysql_query("SELECT * FROM Users WHERE NAME = '".$_POST['username']."'")or die(mysql_error()); $check2 = mysql_num_rows($check); if ($check2 == 0) { die('That user does not exist in our database. Click Here to Register'); } while($info = mysql_fetch_array( $check )) { $_POST['pass'] = stripslashes($_POST['pass']); $info['PASSWORD'] = stripslashes($info['PASSWORD']); $_POST['pass'] = md5($_POST['pass']); if ($_POST['pass'] != $info['PASSWORD']) { die('Incorrect password, please try again.'); } else { $ss = new SecureSession(); $ss->USERNAMEE = $_POST['username']; $ss->check_browser = true; $ss->check_ip_blocks = 2; $ss->secure_word = $_SERVER['REMOTE_ADDR']; $ss->regenerate_id = true; $ss->Open(); $_SESSION['logged_in'] = true; header("Location: members.php"); die(); } } } else { ?>
SLTrinkets
Member Login
Not Signed In.
Username
Password
 
<?php } ?> [/php]

and the session.php

[php]

<?php class SecureSession { // Include browser name in fingerprint? var $check_browser = true; // How many numbers from IP use in fingerprint? var $check_ip_blocks = 0; // Control word - any word you want. var $secure_word = 'SS'; // Regenerate session ID to prevent fixation attacks? var $regenerate_id = true; // Call this when init session. function Open() { $username = ""; $msg = "Welcome " . $username . ", hope you enjoy the site!"; $_SESSION['welcome_msg'] = $msg; // $_SESSION['ss_fprint'] = $this->_Fingerprint(); $this->_RegenerateId(); } // Call this to check session. function Check() { $this->_RegenerateId(); return (isset($_SESSION['ss_fprint']) && $_SESSION['ss_fprint'] == $this->_Fingerprint()); } // Internal function. Returns MD5 from fingerprint. function _Fingerprint() { $fingerprint = $this->secure_word; if ($this->check_browser) { $fingerprint .= $_SERVER['HTTP_USER_AGENT']; } if ($this->check_ip_blocks) { $num_blocks = abs(intval($this->check_ip_blocks)); if ($num_blocks > 4) { $num_blocks = 4; } $blocks = explode('.', $_SERVER['REMOTE_ADDR']); for ($i=0; $i<$num_blocks; $i++) { $fingerprint .= $blocks[$i] . '.'; } } return md5($fingerprint); } // Internal function. Regenerates session ID if possible. function _RegenerateId() { if ($this->regenerate_id && function_exists('session_regenerate_id')) { session_regenerate_id(); } } } ?>

[/php]

just put it at the point where u are settin the other session variables:

[php]

$ss->USERNAMEE = $_POST[‘username’];
$ss->check_browser = true;
$ss->check_ip_blocks = 2;
$ss->secure_word = $_SERVER[‘REMOTE_ADDR’];
$ss->regenerate_id = true;
$ss->Open();
$_SESSION[‘logged_in’] = true;
$msg = "Welcome " . $_POST[‘username’] . “, hope you enjoy the site!”;
$_SESSION[‘welcome_msg’] = $msg;

[/php]

It is working great! And it is simple, but I don’t understand it, can you possibly explain something to me. $_POST[‘username’] in the login form is submitted to its self, How does sessions.php get it? Is the $_post transfered trough includes? Thanks for the help it works great!

Yes, when you do an include of a page the code from the included page is parsed as if it were written right into the rest of the code.

Example:
pagea.php

<?php include("pageb.php"); echo "I AM PAGE A"; ?>

pageb.php

<?php
echo “I A PAGE B”;
?>

This looks to the parser as:
pagea.php

<?php echo "I AM PAGE B"; echo "I AM PAGE A"; ?>

That is very handy to know, I am going from one page to the next, all include the session control and all can see the post. Things like that need to be mentioned in the php manual!!!

PHP basics:

PHP is a server-side script accesed trough the http-protocol.

lets take ur example:

  • the user loads ur domain: http-request on http://www.urdomain.de
  • the apache reacts: as this is a url to a folder (not a file) it searches for index.html, if it would find it would transfer it back via http, but there is no index.html.
  • Apache tries index.php: there is an index.php apache is not transferring it, because it’s a .php-file! apache calls php to process index.php.
  • php runs the code and returns a standard header, as there is no header() in there. then it returns everything that is outside <?php ?> and everything that is echo’d or print()ed as http-body to apache.
  • Apache returns that to the browser
  • the browser recognizes that a header “Content-Type: text/html” was send, and does as if the http-body was html (if it was html the browser would have gotten the exact same header), now the browser is displaying it (graphically: Firefox, IE, safari … / as text: lynx, links2 …).

That was the first life circle, http is a stateless protocol: nobody cares anymore. neither the server nor the client (browser) do anything anymore, no connection is kept up.

Now there was a form on ur page (just guessing) to loggin. It?s displayed by the browser, as well as links (but links are not interesting enough as they just start the already explained life-circle again).

As soon as u press the submit-button the browser acts a little different. it is again staring a http-connection to the browser, but it’s not only transferring the reqest-url (in this case “http://urdomain/login.php” as this was the form-action-value), but also a header that tells the server the “post-vars”. the format is the same as get: username=Q1712&password=hahaiwounttelluoneofmypasswords

Now we start again:

  • apache recives a http-request. this time its a file: login.php. if it was a html-file apache would have returned its content, ignoring the post-vars, again. but as it is a php-file it starts php again (passing all http-headers on to php)
  • php executing the code again, but as there was a post header it is providing its content in a good workable format. that means wile executing the code it does as if there is an array $POST (the '’ is just there because it was adds in php4 and to be still able to execute php3-code it’s not a name sombody may have used as his own variable, and using variables starting with ‘_’ was already depreciated in php3). this array is filled withe the posted vars. arrays are very good to represent the var1=value1&var2=value2… structure. that can be converted in $_POST = array(‘var1’ => ‘value1’, ‘var2’ => ‘value2’, …)
  • not php is running the code again.
  • as soon as php gets to the function session_start() it does somthing special: it is internaly modifying the header it would send to apache (that?s why session_start has to be called before any output, case otherwise php wouldn?t be able to modify it internally, as it has to send the http-header before it is sending the http-body).
  • the modifications that are done: it put a http-header making a cookie. this cookie has the following data: PHP_SESSIONID=5f23e457a30 (just an example)
  • php does one more thing when session_start is called: it creates a file “5f23e457a30” in the session folder (thats the gread thing about sessions, the data is kept on the server)
  • now ur script is executed. and now it shold become clear what happens. whenever u read the $_POST-array it gives u the data just been submitted by the browser (that’s why there is no sense in trying to store something in there). and as soon as u set $_SESSION[‘user’] to a value php modifies that file “5f23e457a30” and writes “user=value” in it.
  • meaning $_SESSION['msg']='Hello '.$_POST['username'] does this: it is accessing the value send by the browser and combines it with "Hello ". and then it stores “msg=Hello%20Q1712” in the file “5f23e457a30”.
  • now there is another header(): “Location: userdata.php” and then php is echoing some data (or not)
  • apache receives this data from php and forwordes it to the browser (the cookie-header PHP_SESSIONID=5f23e457a30 as well as Location: userdata.php)
  • the browser gets the data. now it is reading the headers (with the target to display a html-site) but it get the cookie header, that makes the browser creating a cookie-file with the data “PHP_SESSIONID=5f23e457a30” in it.
  • the next thing the browser reads is the header “Location: userdata.php”. that makes the browser know that it has to react now: it reacts as if the user clicked on a link ‘href=“user.php”’.

there is another life-circle gone. the tings explained now will hapen as well when the user clicks on a link later, but of cause the browser now is reaction on it’s own.

  • the browser sends a new http-request. no form, no post. but it knows there is a cookie. so it wil send the request-url: http://urdomain/user.php and the content of the cookie “PHP_SESSIONID=5f23e457a30” with the http-header.
  • again apache reacts and forwards the cookie-header and the request-url to php.
  • php is reacting as normal: making the cookie-content an array $_COOKIE and running the code. but in that process php automatically detects that there is $_COOKIE[‘PHP_SESSIONID’] and does one more thing: it accesses the file “5f23e457a30” in the session folder and turns it’s content (“user=Q1712&msg=Hello%20Q1712”) in an array called $_SESSION.
  • now the code is run again and it’s output (no special heders [the cookie is already set]) is send to apache and from there to the browser.
  • the browser recognizes the “Content-Type: text/html”-header and displays the http-body as html-file

done

now there is a link in there: 'href=“login.php?logout=logout”

the user clickes on it:

  • a standard http-request is sent to apache (request-url=http://urdomain/login.php?logout=logout)
  • apache makes php run “login.php” but passes “?logout=logout” to php as well
  • php converts “?logout=logout” in $_GET=array(“logout”=>“logout”)
  • php runs if($_GET[‘logout’]) session_destroy();
  • php considers $_GET[‘logout’] to be true
  • php runs session_destroy(): the file “5f23e457a30” in the session folder is deleted.
  • php returns the output (something like “u have been logged out”) to apache, apache to the browser and the browser displays it

that?s all.

let this be a lesson to u: don’t ask Q if u don’t really wanna know :)

[size=99px]**Edited for spelling and grammar only.[/size]

P.S.: if u haven’t understood something plz let me know (i know that i’m thinking to complicated, and that my spelling is u.a.s.)

Its working great now, Thanks!

Sponsor our Newsletter | Privacy Policy | Terms of Service