Session Management in PHP – Part4

We can use session for security checking-like user permission checking on a website while login and destroy this session while the user logout from this site. Generally we use session like following way:

To start a session:
– session_start()
– Creates a session identifier
– Session identifier is passed between client and server either as
a Cookie, or in GET parameters
• Then, can create, access, and modify session variables:
– $_SESSION[session_var_name] = value;
– $_SESSION is only available once you call session_start()
– $local_variable = $_SESSION[session_var_name];
– Can check if session variable is set by using isset();
• To end a session:
– session_destroy();

So at first while loging we register the session variable in login.php:

session_register(‘user_id’);
session_register(‘user_name’);
if($query_data= mysql_fetch_array($result))
{
$_SESSION[‘user_id’] = $query_data[‘user_id’];
$_SESSION[‘user_name’] = $query_data[‘user_name’];
$user_type = $query_data[‘user_type’];
}
if($user_type == “admin”){
header(‘Location:Administrator.php’);
}
else($user_type == “customer”){
header(‘Location:customer.php’);
}

Now from Administrator.php we set following code to check authentication:

session_start( );
if (isset($_SESSION[‘HTTP_USER_AGENT’]))
{
if ($_SESSION[‘HTTP_USER_AGENT’] != md5($_SERVER[‘HTTP_USER_AGENT’]))
{
/* Prompt for password */
/* exit;*/
}
}
else
{
$_SESSION[‘HTTP_USER_AGENT’] = md5($_SERVER[‘HTTP_USER_AGENT’]);
}
echo ‘user is: ‘ . $_SESSION[‘user_name’] . ‘
‘;
?>
if (!isset($_SESSION[‘user_name’])){
?>

}else{

$uid = $_SESSION[‘user_id’]; echo ‘uid is=’.$uid;
//include(“include/db_con.php”);
}
?>

for logout we enter code:

<a href=”logout.php”>Logout</a>

And here is logout.php code:
<?
//start the session
session_start();

//check to make sure the session variable is registered
if(session_is_registered(‘user_name’)){

//session variable is registered, the user is ready to logout
session_unset();
session_destroy();
}
else{

//the session variable isn’t registered, the user shouldn’t even be on this page
header( “Location: http://localhost/yourappfoldername/login.php&#8221; );
}
?>

Now look how fine it works to protect your web from any unauthorized user as well as keep all user track.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: