Session Variables
When a browser loads a new web page, it forgets all the information from the previous page.
A PHP session is a way of storing information within a website, so that it can be retained and used across multiple pages. Sessions work in a similar way to a program. The website code opens (starts) the session. Information is generated, stored and sometimes changed. The website code then closes (destroys) the session to end.
Examples of session use are:
retaining selected items in a shopping cart, as the user navigates from page to page.
displaying a user’s id on multiple pages, following a successful login.
retaining values, such as a user’s quiz Score, when each new question page loads.
Starting a Session
The following PHP function is used to start a session. This should be placed at the top of a page, before any HTML code.
If data is being passed between multiple pages, each page that requires access to the session should contain the PHP code below
PHP Code
<?php
session_start();
?>
<!DOCTYPE html>
<html>
...
When a new session starts, a user key is stored on the user’s computer. The session_start() function looks to see if a user key exists.
If it does, the current session is continued. If no user key exists, a new session is started.
Checking if a session is running.
The code above will create a new session (or continue a previous one) using the session_start function and then it will check if the session variable called counter is set using the (has a value) - it will use the isset() function to do this.
If the session variable called counter has not been set then it will create one and assign it the value of 1. If one does exist then the value is incremented by 1.
Another method to check if a session is running
The code below will execute id a session is not active. If the session is not active then a new one is started.
Session variables could also be used in the context of logins.
The code below will check the password that has been passed to it and then if it is correct will set the userlogin session variable to True. If this happens we will include the main page that we originally had ( but this time the ‘hidden’ content will be visible).
It is possible that when the session is set to true we could include other pages such as a members area, this would depend on the individual site.
The include function inserts the code from the relevant external file. This can be useful to incorporate repeated sections of code.
Session variables could also be used in the context of logins. The skeleton code below could be used to display a login form depending on whether a user is logged in or not. This assumes that when a user is logged in a session variable called userLogin is set to True.
You will notice we have used the password input type.
This is just a text box which will mask the text characters, it will allow the variable to be processed as normal.