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

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...

Pemasangan Joomla! 1.7 pada pelayan web komputer anda

Latihan ini akan memasang sistem pengurusan kandungan laman web ke dalam pelayan web yang anda telah pasang sebelum ini . LANGKAH 1: Aktifkan Pelayan Web dan Pangkalan Data Aktifkan XAMPP Control Panel, melalui “ Start->All Programs->ApacheFriends->XAMPP Control Panel ”. Rajah 2.1 Pastikan pelayan web Apache dan pelayan pangkalan data MySQL diaktifkan dengan klik butang START. -> Rajah 2.2

Installing Google AdMob into Android Apps

Previously I wrote on why ads are needed to help maintaining an app. Read the article here http://blog.kerul.net/2011/05/generating-revenue-from-free-mobile.html . ---This is quite an old article. You may find the latest supporting AdMob 6.x in here http://blog.kerul.net/2012/08/example-how-to-install-google-admob-6x.html --- This is quite a long tutorial, there are 3 major steps involved. The experiment is done using Windows 7, Eclipse Helios and AdMob SDK 4.1.0 (which currently is the latest-during time of writing). STEP 1: Get the ads from AdMob.com To display the AdMob ads in your Android mobile apps, you need to register first at the admob.com . After completing the registration, login and Add Site/App. Refer to Figure 1. Figure 1 Choose the desired platform and fill in the details (as in Figure 2). Just put http:// in the Android Package URL if your app is not published in the market yet. And click Continue. Figure 2 Download the AdMob Android SDK, and save the zip fil...

ViewFlipper Example–a simple FlashCard

UPDATE: Improved with Fling gesture (Sept 2012) UPDATE: ViewFlipper with Flip-In and Flip-Out Animation (August 2012) This tutorial is to demonstrate the ViewFlipper layout that is almost similar to CardLayout (in Java). The app will produce a simple Flash card that provide several screens with different picture for each card. Flip-in and Flip-out animation provided. Added in Sept 2012 – an improvement to support Fling gesture – enjoy… The amendment is only on the coding part. Some how the layout design (main.xml) is quite long. Later I’ll produce separated screen by including several XML layout from outside files. Screenshots;

Submit your blog address here

Create your own blog and send the address by submitting the comment of this article. Make sure to provide your full name, matrix and URL address of your blog. Refer to the picture below. Manual on developing a blog using blogger.com and AdSense, download here … Download Windows Live Writer (a superb offline blog post editor)