PHP Session

A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.

The location of the temporary file is determined by a setting in the php.ini file called session.save_path. Bore using any session variable make sure you have setup this path.

When a session is started following things happen:

  • PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
  • A cookie called PHPSESSID is automatically sent to the user's computer to store unique session identification string.
  • A file is automatically created on the server in the designated temporary directory and bears the name of the unique identifier prefixed by sess_ ie sess_3c7foj34c3jj973hjkop2fc937e3443.

Starting a PHP Session:

A PHP session is easily started by making a call to the session_start() function.This function first checks if a session is already started and if none is started then it starts one. It is recommended to put the call tosession_start() at the beginning of the page. Session variables are stored in associative array called$_SESSION[]. These variables can be accessed during lifetime of a session.

Example

<?php
   session_start();
   if( isset( $_SESSION['counter'] ) )
   {
      $_SESSION['counter'] += 1;
   }
   else
   {
      $_SESSION['counter'] = 1;
   }
   $msg = "You have visited this page ".  $_SESSION['counter'];
   $msg .= "in this session.";
?>
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body>
<?php  echo ( $msg ); ?>
</body>
</html>


PHP : Login and Logout Form with user authentication from MySQL database using session!

Here is an example for user authentication from database ! Create a Table (members) within database(softaid) using MySQL.

membrs

Create a home.php for login by user!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
//Form design for css
<style type="text/css">
#main 
{
width:300px;
margin:50px auto;
font-family:cambria;
}
span 
{
color:red
}
h2 
{
background-color:#DDDAF5;
text-align:center;
border-radius:10px 10px 0 0;
margin:-10px -40px;
padding:15px
}
hr 
{
border:0;
border-bottom:1px solid #ccc;
margin:10px -40px;
margin-bottom:30px
}
#login 
{
width:320px;
border-radius:10px;
font-family:cambria;
border:2px solid #ccc;
padding:10px 40px 25px;
}
input[type=text],input[type=password] 
{
width:99%;
padding:10px;
margin-top:8px;
border:1px solid #ccc;
padding-left:10px;
font-size:16px;
font-family:raleway;
border-radius:10px;
}
input[type=submit] 
{
width:99%;
background-color:#A8A1E6;
color:#fff;
border:2px solid #A8A1E6;
padding:10px;
font-size:20px;
cursor:pointer;
border-radius:5px;
margin-left:10px;
}
#logout 
{
float:right;
padding:5px;
border:dashed 1px gray
}
a 
{
text-decoration:none;
color:#6495ed
}
i 
{
color:#6495ed
}
</style>
</head>
<body>
<?php
session_start(); 
$error='';
if (isset($_POST['submit'])) 
{
    	if (empty($_POST['username']) || empty($_POST['password'])) {
		$error = "Username or Password is invalid ')";
}
else
{
$username=$_POST['username'];
$password=$_POST['password'];
$connection = mysql_connect("localhost", "root", "");
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$db = mysql_select_db("softaid", $connection);
$query = mysql_query("select * from members where password='$password' AND username='$username'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username; 
header("location: profile.php"); 
} else {
$error = "username or password is icorrect!";
}
mysql_close($connection); 
}
}
?>
//Form design for login
<div id="main">
<div id="login">
<h2>Login Form@SOFTAID</h2>
<form action="home.php" method="post">
<br/>
<label>UserName :</label>
<input id="name" name="username" placeholder="username" type="text">
<label>Password :</label>
<input id="password" name="password" placeholder="**********" type="password">
<br />
<br />
<input name="submit" type="submit" value=" Login ">
<span><?php 
if (!empty($error))
{
echo "<script type='text/javascript'>alert('".$error."')</script>";
}?></span>
</form>
</div>
</div>
</body>
</html>

Img3(login)

Press the login Button! after successful user authentication profile.php executed.

img4

Here is profile.php !

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
#profile 
{
padding:50px;
border:1px dashed grey;
font-size:20px;
background-color:#DCE6F7
}
</style>
</head>

<body>

<br />
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("softaid", $connection);

session_start();

$u=$_SESSION['login_user'];

$ses_sql=mysql_query("select * from members where username='$u'", $connection);
$row = mysql_fetch_assoc($ses_sql);

$login_user =$row['username'];
$login_job =$row['job'];

if(!isset($login_user)){
mysql_close($connection); 
header('Location: home.php'); 
}

?>

<div id="profile">
<b id="welcome">Welcome : <i><?php echo $login_user;  ?>  job is : <?php echo $login_job;  ?></i></b>
<b id="logout"><a href="logout.php">Log Out</a></b>
</div>
</body>
</html>