Lecture - 10 - Session
Lecture - 10 - Session
Agenda
• Redirection
• Session
PHP Redirection – Option 1
success.php
Success
Login :
Password :
processLogin.php
Login
Error
Invalid Login and Password !
Error.php
Header(Location:error.php)
PHP Redirection – Option 2
(using parameters)
welcome.php
Success
Login : Success
Password :
processLogin.php
Login
Error
Invalid Login and Password !
Header(Location:login.php?login=no)
PHP Redirection – Option 2
(processLogin.php explained)
<?php //processLogin.php
}
else {
?>
PHP Redirection – Option 2
(login.php explained)
<?php
session_start(); // start a php
session
?>
Storing a session variable
• To store user data in a session use the $_SESSION
associative array.
• You can both store and retrieve session data.
<?php
session_start(); // start a $_SESSION
[‘views’] =1; /store session data
Echo “Pageviews =“ . $_SESSION
[‘views’]
?>
ISSET funtion
• Before using a session variable it is necessary
that you check to see if it exists already !
• isset is a function that takes any variable you
want to use and checks to see if it has been
set
Example 1
• Consider the example in session1.php, a
pageview counter can be created by using
isset to check if the pageview variable has
already been created
• If it has, the counter is incremented. If it does
not exist a pageview counter can be created
and set to one.
Storing and Retrieving Data –
session1.php
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views'] = $_SESSION['views']+ 1;
else
$_SESSION['views'] = 1;
echo "views = ". $_SESSION['views'];
?>
Example 2
• In the following example, a user has to visit
the first page and is then provided access to
the second page
• If user tries to access the second page directly,
he will be redirected to the first page
• Note the use of isset to check whether the
session id has been created – if it has not been
created, user is redirected to first page
Example 2- firstpage.php
<?php
session_start();
$_SESSION['ID']=1234;
?>
<html>
<body>
Check Page – If the user is visiting this page first, then
he will be assigned an ID
<br><a href="secondpage.php">Second Page</a>
</body>
</html>
Example 2- secondpage.php
<?php
session_start();
if(!isset($_SESSION['ID']))
{
header("Location:http://localhost/firstpage.php");
exit();
}
?>
<html>
<body>The user can only view this page if he has gone through the
first page, otherwise he will be redirected to the first page.
</body>
</html>
Cleaning and destroying session
<?php
session_start();
if(isset($_SESSION['cart']))
unset($_SESSION['cart']);
?>