#native_company# #native_desc#

Validating PHP User Sessions Page 5

By PHP Builder Staff
on April 4, 2008

Validating PHP User Sessions


// unset all session variables, and destroy session
function destroySession($p_strMessage) {

if( isset($_SESSION['name']) ) {
	// verify first 6 chars of IP
	if( substr($_SESSION['ip_address'],0,6)
        != substr($_SERVER['REMOTE_ADDR'],0,6) ) {
		destroySession("Invalid IP Address");
	// verify user-agent is same
	elseif( $_SESSION['user_agent'] 
	        != $_SERVER['HTTP_USER_AGENT'] ) {
		destroySession("Invalid User-Agent");
	// verify access within 20 min
	elseif( (time()-1200) > $_SESSION['last_access'] ) {
		destroySession("Session Timed Out");
     // valid session
	else {
		echo("Logged In<br /><br />
		Hello {$_SESSION['name']} 
		Session ID: {$_COOKIE['PHPSESSID']}");
else {
  $_SESSION['name']   		= "John Doe";
  $_SESSION['email']  		= "[email protected]";
  $_SESSION['ip_address']	= $_SERVER['REMOTE_ADDR'];
  $_SESSION['user_agent']	= $_SERVER['HTTP_USER_AGENT'];
  $_SESSION['last_access']	= time();
  echo("Session created, refresh page");


In the above script, we are again loading the information on the first page load, and then just validating the information and outputting it on subsequent loads. To make this script useful, you must do a user login-validation before assigning the user??s data to the session, and if the user??s login is valid, you assign the user-id that you will need to identify that user session and any values that you want quick access to for script operation. However, as you have hopefully seen, PHP makes session handling very easy.
Unfortunately, in many cases, you may want more flexibility than what PHP offers by default–such as the ability to have ??remember me?? functions–but this requires that you set up your own way to store information (generally a database), which then requires that you set up additional algorithms to control when and how sessions get deleted, etc. However, that is going to have to wait for a later article. In the meantime, learning to use PHP sessions will set you up to understand better what you will need in order to develop your own session management application.