Friday 15 April 2011

Sessions and Cookies in PHP

Introduction

Sessions and Cookies enable web developers to store data in a way that is easily accessible from multiple pages. If data is stored using such mechanisms, users will not lose data when navigating from one page to another.
In this blog I will describe my experience and what I’ve learned while performing a task assigned by my tutor.

Cookies

Cookies are stored on the client side and usually are used to identify a user. In PHP a cookie can be created using the following syntax:
setcookie(<Cookie name>,<Cookie value>,<Expire date in seconds>);
Cookies are stored in an array ($_COOKIE), and to retrieve the value of a cookie the following syntax is used:
$_COOKIE[<Cookie name>];
Cookies can be deleted by setting an expired date. For example, the following code deletes ckname cookie.
setcookie("ckname", "", time()-3600);
The isset() function can be used to check if a cookie exists, this returns true if a cookie exists and false if not. Such function is commonly used in an if statement as follows:
If(isset($_COOKIE["ckname"]))
echo "Cookie found";
else
echo "Cookie not found";

Sessions

Session variables are stored on the server and are available to all pages. Sessions related to a user are deleted when the user leaves the web site. When a session is created a unique id (UID) is created and stored in a cookie on the client side, this will be used by the server to identify the user.
Before using sessions, the following syntax is used to start the sessions:
session_start();
The following syntax is used to store a session variable:
$_SESSION[<Session variable name>]=<Value to store>;
If the variable name does not exist, it will be automatically created. A session variable can be destroyed by using the following syntax:
unset($_SESSION[<Session variable name>]);
To destroy completely a session and all its variables, the following syntax can be used:
session_destroy();

Task Description

This blog describes my experience while performing a task assigned by my tutor. The task consists of the following stages:
  • Use PHP to create a login screen that accepts a user and password that are validated on the server side.
  • Add a “remember me” button that uses a cookie so that the user does not have to log in again.
  • Replace the cookie mechanism with PHP sessions

Using Cookies - Login Screen

Design

The log-in page, index.php, enables the user to key-in credentials and log-in to the system. The Remember my credentials enable the user to store a log-in cookie and log-in automatically.
The welcome page, validate.php, displays the user name and enables the user to log-out and delete the log-in cookie.

Flow

The following drawing shows the flow when the index.php page is launched.
Please note that when a ‘Remember me’ cookie exists, the user is redirected automatically to validate.php. When a user clicks the Log-in button in index.php, user name and password keyed in by the user are passed to the validate.php. The following drawing shows flow when the validate.php page is launched.
When a login cookie is found, the cookie value is read and displayed in the welcome page. If the cookie is not present, the user name and password are compared with a text file; containing user accounts. If the account is valid and the ‘Remember Me’ was selected, the log-in cookie is created.
A log me out link will be added to enable the user to log-out and delete the log-in cookie. When this link is clicked, a flag is created and validate.php is launched. As shown in the drawing above, when validate.php is loaded, it checks the flag and if exists the cookie is deleted and the user is redirected to index.php.

Development

The index.php page

In line 42, the script is checking if a parameter ErrorMessage exists. If this parameter exists in lines 43 to 45 an error image and the error text is added to the page.
In line 49, the script is checking if a cookie ckname exists; this is created when Remember my credentials is selected during a log-in. If the cookie exists, the script calls validate.php with a flag checkcookie; this flag is used to instruct validate.php to use the cookie and skip the validation.

The validate.php page

At line 21 the script is checking if a parameter resetCookie exists; this is parameter is created when a user clicks Log-out. If this parameter exists, the script calls resetCookie() function.
The resetCookie() will delete the cookie by setting the expiry date.
In line 31, the script checks if checkcookie parameter exists; this parameter is sent by index.php to use cookies and skip validation. If exists, the cookie value (user name) is stored in a global variable $LoggedinName. In line 35, some text is added to notify the user that log-in was done using cookies.
If checkcookie parameter is not found, the script within lines 37 and 58 is executed. In line 39, the script is checking the user input (username and password). If the input is empty the index.php is launched with an error parameter (Line 55). If the input is not empty, the user name and password are validated using the validateUser(<User name>,<Password>) function; will be explained later in this blog. If the credentials are invalid, the index.php is launched with an error parameter (Line 47).
In line 62, the script checks if Remember my credentials is selected; if selected, a cookie with the username is created.

Test

I will perform some tests to ensure that the system is working as expected.
ü  Test the result when a username and password are not provided and the user clicks Log-in.
ü  Test the result when an invalid username and password are provided.
ü  Test the result when valid credentials are provided and Remember my credentials not selected
ü  Test the result when Remember my credentials is selected and the user tries to access the index.php page for the second time.

Using Sessions - Login Screen

Design

The log-in page, index.php, enables the user to key-in credentials and log-in to the system.
The welcome page, welcome.php, displays the user name and the session id.

Flow

The following drawing shows the flow when the index.php page is launched.
This page contains all the PHP syntax to validate the user, if the user is valid, this page starts a session and calls the welcome.php page. When welcome.php is launched, the session value and the session ID are displayed. The following is the welcome.php flow:
Important to note that sessions can be removed from the client side by closing the Internet browser. In addition the server can be configured to remove the session after a pre defined time, this can be done from a PHP script by adding the following:
ini_set('session.gc_maxlifetime', '<time>');
Where time is an integer in seconds.

Development

The index.php page

In line 7, the isset() function is checking the user input, if the input is not empty the input is validated.
In line 8 using the validateUser(<User name>,<Password>) function, the credentials are validated and if valid the script within lines 9 and 12 is executed.
NOTE: validateUser() function will be explained later in this blog.
In line 10 the session is started and in line 11 a new session (user) having the username is created. At line 12 the welcome.php is called to display the values.
If the credentials are invalid, the error to display is stored in variable $error and displayed using the following code:

The welcome.php page

In line 13 the isset() function is checking if a user session exists. If the session does not exist the user is redirected to the index.php page (line 14). If the session exists, the value is stored in a variable $username and displayed using the following code:
In line 25, the session id is displayed using the session_id() function.

Test

I will perform some tests to ensure that the system is working as expected.
ü  Test the result when an invalid username and password are provided.
ü  Test the result when valid credentials are provided.

Validation

Flow

To validate user credentials, a function was created that gets the user input and compares the credentials with a list stored in a text file. The flow is as follows:

Development

In line 23, using the fopen() function, the file is opened in readonly mode. Iteration is done using a while loop in line 27. Terhehe iteration will loop until the pointer is at the end of file; this is done using the feof() function.
Each line is split in two and stored in an array in line 29; text file is tab delimited.
The array values, $SingleUser[0] and $SingleUser[1] are compared with the $User and the $Password parameters respectively. If these values match the function returns true.
When all text file credentials are checked and no values match the function returns false.

Conclusion

Working with cookies and sessions was an interesting and challenging task. There are more things to learn about this matter and in this blog I’m describing the basics. Hope this helps.
Happy coding…

Resources

Download the session  and the cookie sample files from Windows Live.

No comments:

Post a Comment