COMP519 Web Programming
Lecture 24: PHP (Part 6)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
1 PHP Sessions
2 Authentication
3 Further Reading
COMP519 Web Programming Lecture 24 Slide L24 1
Web Applications Revisited
Select
Item
Enter
Address
Enter
Payment
Confirm
Order
App
App
App
App
App
Request
Response
Request
Response
Request
Response
Request
Response
Request
An interaction between a user and
a server-side web application
often requires a sequence of
requests and responses
For each request, the application
starts from scratch
it does not remember any data
between consecutive requests
it does not know whether the
requests come from the same user
or different users
; data needs to be transferred
from one execution of the
application to the next
COMP519 Web Programming Lecture 24 Slide L24 2
Transfer of Data: Example
Assume the user completes a sequence of forms
By default, a PHP script only has access to the information entered into
the last form
form1.php
< form action = " form2 . php " method = " post " >
<label > Item : < input type =" text " name =" item " > </ label >
</ form >
form2.php
< form action = " process . php " method = " post " >
<label > Address : < input type =" text " name = " addre ss " ></ label >
</ form >
process.php
<? php
echo $ _R EQU EST [ ' item ' ]; echo $ _R EQU EST [ ' addres s ' ];
?>
; PHP Notice: Undefined index ’item’
COMP519 Web Programming Lecture 24 Slide L24 3
Transfer of Data: Hidden Inputs
Assume for a sequence of requests we do not care whether they come
from the same user and whether remembered data has been manipulated
Then hidden inputs can be used for the transfer of data from one
request / page to the next
form1.php
< form action = " form2 . php " method = " post " >
<label > Item : < input type =" text " name =" item " > </ label >
</ form >
form2.php
< form action = " process . php " method = " post " >
<label > Address : < input type =" text " name = " addre ss " ></ label >
< input type =" hidden " name =" item "
value =" <? php echo $ _REQU EST [ ' item '] ?> " >
</ form >
process.php
<? php
echo $ _R EQU EST [ ' item ' ]; echo $ _R EQU EST [ ' addres s ' ];
?>
COMP519 Web Programming Lecture 24 Slide L24 4
PHP Sessions
Sessions
Assume for a sequence of requests we do care that they come from the
same user and that remembered data has not been manipulated
Sessions help to solve this problem by associating client requests with a
specific user and maintaining data over a sequence of requests from
that user
Sessions are often linked to user authentication but are independent of
it, for example, eCommerce websites maintain a ‘shopping basket’
without requiring user authentication first
However, sessions are the mechanism that is typically used to allow or
deny access to web pages based on a user having been authenticated
COMP519 Web Programming Lecture 24 Slide L24 5
PHP Sessions
Sessions
Servers keep track of a user’s sessions by using a session identifier,
which
is generated by the server when a session starts
is remembered by the browser
is then send by the browser with every further HTTP request to that server
is forgotten by the browser when the session ends or the browser is closed
In addition, the server can use session variables for storing information
that relate to a session (session data), for example,
the items of an order
Sessions variables only store information temporarily
If one needs to preserve information between visits by the same user,
one needs to consider a method such as using a persistent cookie or a
database to store such information
COMP519 Web Programming Lecture 24 Slide L24 6
PHP Sessions
Cookies
Browser Server
GET /index.html HTTP/1.1
Host: intranet.csc.liv.ac.uk
Browser Server
HTTP/1.0 200 OK
Content-type: text/html
Set-Cookie: name1=value1
Set-Cookie: name2=value2; Expires= Thu, 20 Mar 2014, 14:00 GMT
(content of index.html)
Browser Server
GET /teaching.html HTTP/1.1
Host: intranet.csc.liv.ac.uk
Cookie: name1=value1; name2=value2
Accept: */*
Browser Server
HTTP/1.0 200 OK
Content-type: text/html
Set-Cookie: name1=value3
Set-Cookie: name2=value4; Expires= Fri, 21 Mar 2014, 14:00 GMT
Set-Cookie: name3=value5; Expires= Fri, 28 Mar 2014, 20:00 GMT
(content of teaching.html)
Wikipedia Contributors: HTTP Cookie. Wikipedia, The Free Encyclopedia, 5 March 2014 20:50.
http://en.wikipedia.org/wiki/HTTP_cookie [accessed 6 Mar 2014]
COMP519 Web Programming Lecture 24 Slide L24 7
PHP Sessions
PHP Sessions
Sesssions proceed as follows
1 Start a PHP session
bool session_start()
string session_id([id])
bool session_regenerate_id([delete_old])
2 Maintain session data
bool session_start()
$_SESSION array
bool isset($_SESSION[key])
(interacting with a database)
3 End a PHP session
bool session_destroy()
void session_unset()
bool setcookie(name, value, expires, path)
COMP519 Web Programming Lecture 24 Slide L24 8
PHP Sessions Start a PHP Session
Start a Session
bool session_start()
creates a session
creates a session identifier (session id) when a session is created
sets up $_SESSION array that stores session variables and session data
the function must be executed before any other header calls
or output is produced
string session_id([id])
get or set the session id for the current session
the constant SID can also be used to retrieve the current name and
session id as a string suitable for adding to URLs
string session_name([name])
returns the name of the current session
if a name is given, the current session name will be replaced with the given
one and the old name returned
COMP519 Web Programming Lecture 24 Slide L24 9
PHP Sessions Start a PHP Session
Start a PHP Session
bool session_regenerate_id([delete_old])
replaces the current session id with a new one
by default keeps the current session information stored in $_SESSION
if the optional boolean agument is TRUE, then the current session
information is deleted
; regular use of this function alleviates the risk of a session
being ‘hijacked’
<? php
ses si on_ start ();
echo " S essio n id : " , ses sio n_i d () , "<br >" ;
echo " S essio n name : " , ses sio n_nam e () , " <br > " ;
se ssion _r eg en er ate_id ();
echo " S essio n id : " , ses sio n_i d () , "<br >" ; // changed
echo " S essio n name : " , ses sio n_nam e () , " <br > " ; // uncha nge d
?>
COMP519 Web Programming Lecture 24 Slide L24 10
PHP Sessions Maintain Session Data
Maintain Session Data
bool session_start()
resumes the current session based on a session identifier
passed via a GET or POST request, or passed via a cookie
restores session variables and session data into $_SESSION
the function must be executed before any other header calls
or output is produced
$_SESSION array
an associative array containing session variables and session data
you are responsible for choosing keys (session variables)
and maintaining the associated values (session data)
bool isset($_SESSION[key])
returns TRUE iff $_SESSION[key] has already been assigned a value
COMP519 Web Programming Lecture 24 Slide L24 11
PHP Sessions Maintain Session Data
Maintain Session Data
bool session_start()
$_SESSION array
bool isset($_SESSION[key])
<? php
// Cou nting the number of page request s in a sessi on
// Each web page con tain s the follo win g PHP code
ses si on_ start ();
if (! isset ( $_SE SSI ON [ ' reques ts ' ]))
$_S ESSION [ ' re quests ' ] = 1;
else
$_S ESSION [ ' re quests ' ]++;
echo "# Req uests in this ses sion so far : " ,
$_S ESSION [ ' re quests ' ] ," <br / >\ n ";
?>
COMP519 Web Programming Lecture 24 Slide L24 12
PHP Sessions End a PHP Session
End a PHP Session
bool session_destroy()
destroys all of the data associated with the current session
it does not unset any of the global variables associated with the session,
or unset the session cookie
void session_unset()
frees all session variables currently registered
bool setcookie(name, value, expires, path)
defines a cookie to be sent along with the rest of the HTTP headers
must be sent before any output from the script
the first argument is the name of the cookie
the second argument is the value of the cookie
the third argument is time the cookie expires (as a Unix timestamp), and
the fourth argument is the parth on the server in which the cookie will be
available
COMP519 Web Programming Lecture 24 Slide L24 13
PHP Sessions End a PHP Session
End a PHP Session
bool session_destroy()
destroys all of the data associated with the current session
void session_unset()
frees all session variables currently registered
bool setcookie(name, value, expires, path)
defines a cookie to be sent along with the rest of the HTTP headers
<? php
ses si on_ start ();
ses si on_ unset ();
if ( session _id () != "" || isset ( $ _C OOKI E [ s ess ion _n ame ()]))
// force the cookie to expire
setcookie ( ses sio n_nam e () , s ess ion _id () , time () -2592000 , '/ ' );
sessi on_de st roy ();
?>
Note: Closing your web browser will also end a session
COMP519 Web Programming Lecture 24 Slide L24 14
PHP Sessions End a PHP Session
Transfer of Data: Sessions (Part 1)
Assume for a sequence of requests we do care whether they come from
the same user or different users
form1Session.php (no changes)
< form action = " for m2S essio n . php " method = " post " >
<label > Item : < input type =" text " name =" item " ></ label >
</ form >
Starting/maintaining a session for the first form is optional
COMP519 Web Programming Lecture 24 Slide L24 15
PHP Sessions End a PHP Session
Transfer of Data: Sessions (Part 2)
Assume for a sequence of requests we do care whether they come from
the same user or different users
form2Session.php
<? php
ses si on_ start ();
if ( isset ( $ _ REQUEST [ ' item ' ]))
$_S ESSI ON [ ' name '] = $ _ REQ UEST [ ' item ' ];
?>
<! D OCTYPE html >
< html lang = 'en - GB ' >
<head >< title > Form 2 </ title > </ head >
<body >
< form action = " pro ce ssS es sio n . php " method =" post " >
<label > Address : < input type = " text " name = " addre ss ">
</ label >
<!- - no hidden input re quir ed -- >
</ form >
</ body >
</ html >
COMP519 Web Programming Lecture 24 Slide L24 16
PHP Sessions End a PHP Session
Transfer of Data: Sessions (Part 3)
Assume for a sequence of requests we do care whether they come from
the same user or different users
processSession.php
<? php
ses si on_ start ();
// not ne ces sary but co nve nie nt
if ( isset ( $ _ REQUEST [ ' addre ss ' ]))
$_S ESSI ON [ ' ad dress '] = $ _RE QUEST [ ' add ress ' ];
?>
<! D OCTYPE html >
< html lang = 'en - GB ' >
<head >< title > Processing </ title > </ head >
<body >
<? php
echo $ _S ESS ION [ ' item ' ]; echo $ _S ESS ION [ ' addres s ' ];
// Once we do not need the data anymore , get rid of it
ses si on_ unset (); sessi on_de st roy ();
?>
</ body > </ html >
COMP519 Web Programming Lecture 24 Slide L24 17
PHP Sessions Session Management
More on Session Management
The following code tracks whether a session is active and ends the session
if there has been no activity for more then 30 minutes
if ( isset ( $ _S E SSI ON [ ' LAS T _ACT I VITY ' ]) &&
( time () - $_ SESS ION [ ' LA ST_A C TIVI T Y ' ] > 180 0)) {
// la st req uest was more than 30 mina tes ago
se s s ion_ d estr o y (); // de stroy sessio n data in st orage
se s sion _ unse t (); // unset ses sion va ria b les
if ( s essi on_ i d () != " " || is set ( $ _ C OOK IE [ se s sio n _nam e ()]) )
se tco o kie ( s essi o n_n a me () , se ssi o n_i d () , tim e () -2 592000 , '/ ' );
} else {
// upd ate last ac tiv ity ti me st am p
$_ SESS ION [ ' LA S T_AC T IVI T Y '] = time ();
}
The following code generates a new session identifier every 30 minutes
if (! isset ( $ _S ESSI ON [ ' CR EAT ED ' ])) {
$_ SESS ION [ ' CREA TED '] = time ();
} else if ( time () - $_ S ESS ION [ ' CREA TED '] > 180 0) {
// s essio n start ed more than 30 minate s ago
se s s i on_r e g e nera t e _id ( true );
$_ SESS ION [ ' CREA TED '] = time ();
}
http://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session- after- 30-minutes
COMP519 Web Programming Lecture 24 Slide L24 18
PHP Sessions Example
PHP Sessions: Example
mylibrary.php:
<? php
ses si on_ start ();
function d estroy_se ss io n_ an d_ da ta () {
ses si on_ unset ();
if ( session _id () != "" || isset ( $ _C OOKI E [ s ess ion _n ame ()]))
setcookie ( ses sio n_nam e () , s ess ion _id () , time () -2592000 , '/ ' );
sessi on_de st roy ();
}
function co un t_r eq ues ts () {
if (! isset ( $_SE SSI ON [ ' reques ts ' ]))
$_S ESSION [ ' re quests ' ] = 1;
else $ _S ESS ION [ ' reque sts ' ]++;
return $ _S ESS ION [ ' r eque sts ' ];
}
?>
COMP519 Web Programming Lecture 24 Slide L24 19
PHP Sessions Example
PHP Sessions: Example
page1.php:
<? php
req uire_ onc e ' myl ibr ary . php ';
echo " < html lang =\" en - GB \" > < head > </ head >< body >\ n ";
echo " Hello visi tor !< br /> This is your page req uest no " ;
echo co unt_r eques ts (). " from this site . < br / >\ n" ;
echo ' <a href =" page1 . php " > Continue </ a > |
<a href =" fi nish . php " > Finish </a > </ body > ';
?>
finish.php:
<? php
req uire_ onc e ' myl ibr ary . php ';
de st roy_sessi on _a nd _d at a ();
echo " < html lang =\" en - GB \" > < head > </ head >< body >\ n ";
echo " G oodby e vis itor !< br / >\n" ;
echo ' <a href =" page1 . php " > Start again </a > </ body > ';
?>
http://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/page1.php
COMP519 Web Programming Lecture 24 Slide L24 20
PHP Sessions Example
PHP and Cookies
Cookies can survive a session and transfer information from one session to
the next
cmylibrary.php:
<? php
ses si on_ start ();
function d estroy_se ss io n_ an d_ da ta () { // unchan ged }
function co un t_r eq ues ts () {
if (! isset ( $_COOKIE [ ' r eque sts ' ])) {
set cookie ( ' re quests ' , 1 , time ( )+3153 6000 , ' / ' );
return 1;
} else {
// $ _C OOKIE [' request s ']++ would not survive , in stead use
set cookie ( ' re quests ' , $ _COOKIE [ ' r eque sts ' ]+1 ,
time ()+31536000 , '/ ' ); // val id for 1 year
return $ _C OOKI E [ ' request s ' ]+1;
} }
?>
http://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/cpage1.php
COMP519 Web Programming Lecture 24 Slide L24 21
Authentication Overview
PHP Sessions and Authentication
Sessions are the mechanism that is typically used to allow or deny
access to web pages based on a user having been authenticated
Outline solution:
We want to protect a page content.php from unauthorised use
Before being allowed to access content.php, users must first authenticate
themselves by providing a username and password on the page login.php
The system maintains a list of valid usernames and passwords in a database
and checks usernames and passwords entered by the user against that
database
If the check succeeds, a session variable is set
The page content.php checks whether this session variable is set
If the session variable is set, the user will see the content of the page
If the session variable is not set, the user is redirected to login.php
The system also provides a logout.php page to allow the user to log out
again
COMP519 Web Programming Lecture 24 Slide L24 22
Authentication Example
PHP Sessions and Authentication: Example
content.php:
<? php
ses si on_ start ();
if (! isset ( $_SE SSI ON [ ' user ' ])) {
// User is not logged in , redirect ing to login page
header ( ' Location : login . php ' );
}
?>
<! D OCTYPE html >
< html lang =" en - GB " >
<head >< title > Cont ent that requi res login </ title > </ head >
<body >
<h1 > Prot ect ed Content </ h1 >
<b > Wel come <i > <? php echo $_S ESSION [ ' user '] ? > </ i > </b > < br / >
<b > <a href =" logout . php " > Log Out </ a > </b >
</ body >
</ html >
http://cgi.csc.liv.ac.uk/
~
ullrich/COMP519/examples/content.php
COMP519 Web Programming Lecture 24 Slide L24 23
Authentication Example
PHP Sessions and Authentication: Example
Second part of login.php:
<! D OCTYPE html >
< html lang =" en - GB " >
<head >< title > Login </ title > </ head >
<body >
<h1 > Login </ h1 >
< form action = "" method =" post ">
<label > Use rname :
< input name =" user " placeho lde r =" usernam e " type =" text " >
</ label >
<label >
Password :
< input name =" passwd " placeh old er =" ** " type = " passwor d " >
</ label >
< input name =" submit " type =" submi t " value = " login " >
<span > <? php echo $ error ; ? > </ span >
</ form >
</ body >
</ html >
http://cgi.csc.liv.ac.uk/
~
ullrich/COMP519/examples/login.php
COMP519 Web Programming Lecture 24 Slide L24 24
Authentication Example
PHP Sessions and Authentication: Example
First part of login.php:
<? php
sessio n _ s t a r t ();
fu n ction checkCredentials ( $user , $pa s swd ) { // Authen t i c a t e the u ser
}
fu n ction ne xtLoc () { // Compu t e next locatio n
}
$e rror = ' ' ;
if ( isset ( $ _ POST [ ' subm it ' ])) {
if ( checkCredentials ( $ _ R EQUEST [ ' use r '] , $_ R EQUEST [ ' p assw d ' ])) {
$_S E S S ION [ ' user ' ]= $_R E Q U EST [ ' u ser ' ];
he ader (" loca t ion : " . nextLo c ()); // R e d i r ecting to conte nt
} else {
$e rror = " U s ername or Pass w ord is inval id . Try Agai n " ;
}
}
if ( isset ( $_ S ESSION [ ' user ' ])){
he ader (" loca t ion : " . nextLo c ());
}
?>
COMP519 Web Programming Lecture 24 Slide L24 25
Authentication Example
PHP Sessions and Authentication: Example
nextLoc():
fu n ction ne xtLoc () {
// W orks out w here to send the user after they have been aut h e n t i c a t e d
if (( bas e name ( $ _SERV E R [ ' HTTP_REFERER ' ]) == ' login . php ') ||
( base n ame ( $ _SERVE R [ ' HTTP_REFERER ' ]) == ' logo ut . php ' )) {
// If the user came from the logi n or logo ut page ,
// send the user to the ` defau lt ' pag e .
re turn " con tent . php " ;
} else {
// Othe rwise , send the user to where they c ame from .
re turn $_ SERVER [ ' H T T P _ R E FERER ' ];
}
}
COMP519 Web Programming Lecture 24 Slide L24 26
Authentication Example
PHP Sessions and Authentication: Example
logout.php:
<? php
ses si on_ start ();
$user = $ _SE SSIO N [ ' user ' ];
ses si on_ unset ();
sessi on_de st roy ();
?>
<! D OCTYPE html >
< html lang =" en - GB " >
<head >
<title > Logout </ title >
</ head >
<body >
<h1 > Logout </ h1 >
<b > Goo dbye <i > <? php echo $user ? > </ i > </b > < br / >
<b > <a href =" login . php " > Login </ a > </b >
</ form >
</ body >
http://cgi.csc.liv.ac.uk/
~
ullrich/COMP519/examples/logout.php
COMP519 Web Programming Lecture 24 Slide L24 27
Further Reading
Revision and Further Reading
Read
Chapter 12: Cookies, Sessions, and Authentication
of R. Nixon: Learning PHP, MySQL & JavaScript:
with jQuery, CSS & HTML5. O’Reilly, 2018.
COMP519 Web Programming Lecture 24 Slide L24 28