Skip to main content

Server-side Sessions in a web server–Apache + PHP

session illustrated

(Pic Source: http://download.oracle.com/docs/cd/B14099_19/web.1012/b15901/sessions008.htm)

So, what is SESSION?

Session in term of server-side scripting concern is the connection between a client (browser) and the server that hosting the web application. Each time a client connects to a web server, there is a connection happens. The connection can be registered in the server and there are a lot of information regarding the connection that can be recorded in the web server. For example the web browser being used or the IP number.

Starting a session

Each unique connection provides a unique session id. To enable the session management of a page, first the session_start() function must be executed. This function can only work if there is no information from the page was sent to the client, not even a space or a single bit.

For example, try the following code.

<html>
<head>
<title>Session Testing</title>
</head>

<body>
<?php
session_start();
//trying to start session management
?>

The session management in this page won't work, because there are a lot of characters has been sent to the client before the session_start() is executed.

</body>
</html>



Output of the script.


clip_image003


This example also doesn’t work. The problem is caused by only a newline (‘\n’) character before the session_start() function.

clip_image006

Output of the script.


clip_image008


At last, a working example.


clip_image010


The code;



<?php
session_start();
?>
<html>
<head>
<title>Session Testing</title>
</head>

<body>
The session management WORKS!<br>
<?php
echo "The session id: ".session_id();
?>

</body>
</html>

The output of the script.

clip_image012


So where is this session information is stored?


Currently we are using XAMPP. By default the Apache web server store the session information in the tmp directory. Each session will generate a file with the sess_ as the prefix, and followed by the session id.


clip_image014


Try to open the file and you will nothing is stored in the file where the latest session was created using the script in previous page. This is because there is no session variable is registered.


Session variable registration need to be done in order to store values to be used as long as the session (or the connection) is established. For example, in a web application there are few files connected to each other. In order to maintain a certain amount of value to be used for every pages in the system, we need to store it in the session variable. For example the username of the user who are using the system.


Registering a session variable


To store the username (so that all the pages in the system will be displaying the same username) we need to register a session variable. The following script is to register few session variable.


<?php session_start(); ?>

<html>
<head>
<title>Session Registration</title>
</head>
<body>

This page is to register user's information.<br>
<?php
if(!isset($_SESSION['
sessionid'])){
$_SESSION['
sessionid']=session_id();//session id
$_SESSION['
browser']=$_SERVER['HTTP_USER_AGENT'];//browser
$_SESSION['
ipnumber']=$_SERVER['REMOTE_ADDR'];//client's ip
$_SESSION['username']="kerul";//the username
$_SESSION['name']="Khirulnizam Abd Rahman";//full name
$_SESSION['level']=1;//user access level
}
echo "Session id: ".$_SESSION['sessionid']."<br>";
echo "User browser: ".$_SESSION['browser']."<br>";
echo "Client IP: ".$_SESSION['ipnumber']."<br>";
?>

</body>

</html>


The script provide the registration of four session variable namely; sessionid, username, name and level, with their respective value.


Now open the file where the server store the session id in notepad.


clip_image015


This is the content of the session file.


clip_image017


Checking the session variable.


<?php
session_start();
?>
<html>
<head>
<title>Session Checking</title>
</head>

<body>
This page is to check whether user's information are stored in the session.<br>
<?php
if (isset($_SESSION['
sessionid'])){
echo $_SESSION['
sessionid'] .'<br>';
echo $_SESSION['
browser'].'<br>';
echo $_SESSION['
ipnumber'].'<br>';
echo $_SESSION['
username'] .'<br>';
echo $_SESSION['
name'] .'<br>';
echo $_SESSION['
level'] .'<br>';
}
else{
$_SESSION['
sessionid']=session_id();
$_SESSION['
browser']=$_SERVER['HTTP_USER_AGENT'];
$_SESSION['
ipnumber']=$_SERVER['REMOTE_ADDR'];
$_SESSION['
username']="kerul";
$_SESSION['
name']="Khirulnizam Abd Rahman";
$_SESSION['
level']=1;
}
?>

</body>
</html>


Using the session variable.



<?php session_start(); ?>
<html>
<head>
<title>Session Usage</title>
</head>

<body>

This page is to use user's information stored in session.<br>
<?php
echo $_SESSION['
sessionid'].'<br>';
echo $_SESSION['
browser'].'<br>';
echo $_SESSION['
ipnumber'].'<br>';
echo $_SESSION['
username'] .'<br>';
echo $_SESSION['
name'] .'<br>';
echo $_SESSION['
level'] .'<br>';
?>

</body>

</html>

Destroy the session variable.

 



<?php
session_start();
?>

<html>
<head>
<title>Session Destroy</title>
</head>

<body>
This page is to destroy a session.<br>
<?php
if (isset($_SESSION['sessionid'])){
session_destroy();//this to destroy all session info
}
?>

</body>
</html>

Get the PDF documents from Scribd.com ...

SIMPLE EXAMPLE


Protect ur Treasure App!


This simple application is to illustrate the usage of server session. You have two web pages; a page that contains your ‘treasure’, and another page which is the guardian of the ‘treasure’. In order for the right user to acquire your ‘treasure’, the person need to provide the right username and password to the guardian (login page).


1st page – the login page (guardian) – session registration.guardian


File name: guardian.php


<?php session_start() ?>
<html>
<head>
<title>Session Register</title>
</head>

<body>
I'm the guardian!<br>
<img src="guardian.jpg"><br>
Provide username and password to discover the treasure!<br>
<form method='
GET' action="">
Username <input type="text" name="username"><br>
Password <input type="password" name="psword"><br>
Password <input type="submit" value="Unlock"><br>
</form>
<hr>
Message from the Guardian!<br>
<?php
$usrname=$_GET['
username'];
$usrpswd=$_GET['
psword'];
//guardian password
$guard_username="kerul";
$guard_password="kerul.net";
if ($usrname==NULL || $usrpswd==NULL){
echo "Provide the information, human!<br>";
}
else{
if($usrname==$guard_username && $usrpswd==$guard_password){
//allowed to enter
echo "<a href='
treasure.php'>Click to get ur treasure</a><br>";
//set the session
if(!isset($_SESSION['
sessionid'])){
$_SESSION['
sessionid']=session_id();//session id
$_SESSION['
username']=$usrname;//the username
}
}
else{
echo "You have no right to the treasure, <br>";
echo "you might wanna try again!";
}
}
?>
</body>
</html>


2nd page – the treasure – session checking.treasure


File name: treasure.php


<?php
//this script is to check session to verify user login
session_start();
if(!isset($_SESSION["username"])){ //if session NOT set
echo "You are not authorised, human".
"<a href='guardian.php'>Click here to login.</a>";
exit(0);
}
?>

<html>
<head>
<title>Session Checking and Usage</title>
</head>
<body>

<?php
echo "You deserve the treasure,".$_SESSION['username']."!<br>";
?>

<img src="treasure.jpg"><br>

Once finished, <a href="lock.php">LOCK the treasure back!</a>


</body>
</html>


3rd page – logout - session destroyer.


File name: lock.php


<?php
session_start();
?>

<html>
<head>
<title>Session Destroy</title>
</head>

<body>

<?php
if (isset($_SESSION['username'])){
session_destroy();//this to destroy all session info
}
?>
The treasure has been LOCKED. <br>
<a href="guardian.php">Meet the guardian to UNLOCK!</a><br>

</body>
</html>


Download codes here –>

Comments

  1. As u said b4, human got no power, power comes from the human creator...

    ReplyDelete

Post a Comment

Popular posts from this blog

Several English proverbs and the Malay pair

Or you could download here for the Malay proverbs app – https://play.google.com/store/apps/details?id=net.kerul.peribahasa English proverbs and the Malay pair Corpus Reference: Amir Muslim, 2009. Peribahasa dan ungkapan Inggeris-Melayu. DBP, Kuala Lumpur http://books.google.com.my/books/about/Peribahasa_dan_ungkapan_Inggeris_Melayu.html?id=bgwwQwAACAAJ CTRL+F to search Proverbs in English Definition in English Similar Malay Proverbs Definition in Malay 1 Where there is a country, there are people. A country must have people. Ada air adalah ikan. Ada negeri adalah rakyatnya. 2 Dry bread at home is better than roast meat home's the best hujan emas di negeri orang,hujan batu di negeri sendiri Betapa baik pun tempat orang, baik lagi tempat sendiri. 3 There's no accounting for tastes We can't assume that every people have a same feel Kepala sama hitam hati lain-lain. Dalam kehidupan ini, setiap insan berbeza cara, kesukaan, perangai, tabia

Contact Us at blog.kerul.net

Powered by EMF HTML Contact Form

Login JSON Android using Login Activity

I’ve been trying to release this tutorial quite a while. At last after a long hard effort. Since HttpClient is not supported any more in Android SDK 23, I have to resort to org.json.JSONObject and java.net.HttpURLConnection library to do online database with JSON. The objective of this tutorial is to log-in from a mobile client with the username and password stored in an online database facility. STEP 1: Create a new Android project, this time choose the LoginActivity .

Bootstrap Template for PHP database system - MyCompanyHR

HTML without framework is dull. Doing hard-coded CSS and JS are quite difficult with no promising result on cross platform compatibility. So I decided to explore BootStrap as they said it is the most popular web framework. What is BootStrap? - Bootstrap is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first web sites. (  http://www.w3schools.com/bootstrap/   ) Available here -  http://getbootstrap.com/ Why you need Flat-UI? Seems like a beautiful theme to make my site look professional. Anyway you could get variety of BootStrap theme out there, feel free to select here  http://bootstraphero.com/the-big-badass-list-of-twitter-bootstrap-resources/ Flat-UI is from DesignModo -   http://designmodo.com/flat/ Web Programming MyCompanyHR – PHP & MySQL mini project (with Boostrap HTML framework) Template 1: Template for the Lab Exercise. This is a project sample of a staff record management system. It has the PHP structured co

Pick a file using Intent.ACTION_GET_CONTENT

This tutorial is tested on Honeycomb 3.0 environment. In order to be used it in the lower level of Android API, I believe you could just change the target in the Android project. Screenshots Pick an image file using Intent.ACTION_GET_CONTENT The intention of this project is to choose an image file available in the device storage, and simply display it in an ImageView. The benefit of using Intent.ACTION_GET_CONTENT is you don’t have to develop open dialog box which is not available in the Android library. ACTION_GET_CONTENT with MIME type */* and category CATEGORY_OPENABLE -- Display all pickers for data that can be opened with ContentResolver.openInputStream() , allowing the user to pick one of them and then some data inside of it and returning the resulting URI to the caller. This can be used, for example, image chooser (as shown in this article).