Session maintenance in PHP

Today we will see how we can maintain login sessions in php. 🙂

Here we are considering a simple example for 4 pages. One is index page(login page) and index_action,home,logout page respectively. As we are connecting login page to sql server remotely, here connection syntax will be in sql server syntax. When ever user login with different credentials which is not located in sql server db then it returns to index page again. If he enters proper credentials, then login to home page. When ever user clicks signout from homepage, session will be destroyed immediately.

Index Page:

<form id=”login”method=”post” action=”index_action.php? run=1″>

Index_action Page:

<?php
ob_start();
session_start();

header(“Cache-Control: no-cache, no-store, must-revalidate, post-check=0, pre-check=0”);
header(“Pragma: no-cache”);
$v1 = isset($_REQUEST[‘run’]) ? $_REQUEST[‘run’] : 0 ;
if($v1==1)
{

$a = $_POST[“username”];
$b = $_POST[“password”];

}
$serverName = “serverName\instanceName”;

$connectionInfo = array(
‘Database’ => ‘DBName’,
‘UID’ => ‘userid’,
‘PWD’ => ‘pwd’);
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
echo “Connection established.<br />”;
}else{
echo “Connection could not be established.<br />”;
die( print_r( sqlsrv_errors(), true));
}
$query = “Stored_Procedure_name ‘$a’,’$b'”;
$params = array();
$result1 = sqlsrv_query($conn, $query, $params);
$result2 = sqlsrv_fetch_array($result1);
echo $result2[UserID];
if($result2[UserID])
{
$_SESSION[‘session_name’] = $result2[UserID];

header(“Location:home.php”);
}
else{

header(“Location:index.php?err=1”);

}

?>

Home Page:

<?PHP
session_start();

if(!isset($_SESSION[‘session_name’]))
{
header(“Location: index.php”);
}

?>

<a href=”logout.php” title=”Sign out”>Sign Out</a>

Logout Page:

<?php
session_start();
unset($_SESSION);
session_destroy();
header(“Location:index.php”);
?>

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