COMP284 Scripting Languages
Lecture 7: PHP (Part 5)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
1 Web applications
Overview
HTML forms
2 Available information and Input
Overview
PHP environment
Server variables
Form data
3 PHP sessions
Start a PHP session
Maintain session data
End a PHP session
Session management
Example
4 Authentication
Overview
Example
COMP284 Scripting Languages Lecture 7 Slide L7 1
Web applications Overview
Web applications using PHP
IBM: Build Ajax-based Web sites with PHP, 2 Sep 2008.
https://www.ibm.com/developerworks/library/wa-aj-php/ [accessed 6 Mar 2013]
COMP284 Scripting Languages Lecture 7 Slide L7 2
Web applications HTML forms
HTML forms
When considering Pythan CGI programming we have used HTML forms
that generated a client request that was handled by a Python CGI
program:
< form action = ' process . py ' method = ' post ' >
...
</ form >
Now we will use a PHP script instead:
< form action = ' process . php ' method = ' post ' >
...
</ form >
The PHP script file must be stored in a directory accessible by the web
server, for example $HOME/public_html, and be readable by the web
server
The PHP script file name must have the extension .php, e.g. demo.php
COMP284 Scripting Languages Lecture 7 Slide L7 3
Available information and Input Overview
Information available to PHP scripts
Information about the PHP environment
Information about the web server and client request
Information stored in files and databases
Form data
Cookie/Session data
Miscellaneous
string date(format)
returns the current date/time presented according to format
for example, date('H:i l, j F Y')
results in 12:20 Thursday, 8 March 2012
(See http://www.php.net/manual/en/function.date.php)
int time()
returns the current time measured in the number of seconds
since January 1 1970 00:00:00 GMT
COMP284 Scripting Languages Lecture 7 Slide L7 4
Available information and Input PHP environment
PHP environment
phpinfo([part])
displays information about the PHP installation and EGPCS data
(Environment, GET, POST, Cookie, and Server data)
for the current client request
if the optional part is specified, only displays selected information
INFO_GENERAL The configuration, php.ini location, build
date, web server
INFO_CONFIGURATION Local and master values for PHP directives
INFO_MODULES Loaded modules
INFO_VARIABLES All EGPCS data
< html lang = ' en - GB ' >< head > </ head >< body >
<? php
phpi nfo (); // Show all in for mat ion
phpi nfo ( IN FO_VA RIABL ES ); // Show only info on EGPCS data
?>
</ body > </ html >
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/phpinfo.php
COMP284 Scripting Languages Lecture 7 Slide L7 5
Available information and Input PHP environment
Manipulating the PHP configuration
The following functions can be used to access and change the
configuation of PHP from within a PHP script:
array ini_get_all()
returns all the registered configuration options
string ini_get(option)
returns the value of the configuration option option
string ini_set(option, value)
sets the value of the given configuration option to a new value
the configuration option will keep this new value during the script’s
execution and will be restored afterwards
void ini_restore(option)
restores a given configuration option to its original value
COMP284 Scripting Languages Lecture 7 Slide L7 6
Available information and Input PHP environment
Manipulating the PHP configuration: Debugging
By default, our web server does not make errors, notices, and warnings
visible to the user
This can be changed using ini_set with the display_errors option
Via the error_reporting function we can then extend what is
reported by PHP
< html lang = ' en - GB ' >< head > </ head >< body >
<? php
ini_ set ( ' d is pla y_ err or s ' ,1);
error _repo rt ing ( E_ALL | E_ST RICT );
echo ' <p > The value of 1 divided by 0 is ' ,1/0 , ' </p > ';
?>
</ body > </ html >
COMP284 Scripting Languages Lecture 7 Slide L7 7
Available information and Input Server variables
Server variables
The $_SERVER array stores information about the web server
and the client request
; Corresponds to os.environ array in Python CGI programs
< html lang = ' en - GB ' >< head > </ head >< body >
<? php
echo ' Server softw are : ' , $ _SER VER [ ' SE RVE R_ SOFTW ARE ' ] , ' <br > ' ;
echo ' Remote addres s : ' , $_SERVE R [ ' RE MOT E_A DDR ' ] , '<br > ' ;
echo ' Client browse r : ' , $_SERVE R [ ' HT TP _USER _A GEN T ' ] , ' <br > ' ;
echo ' Re quest metho d : ' , $_SERVE R [ ' RE QU EST _M ETH OD ' ];
? > </ body > </ html >
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/server.php
Server sof twar e : A pache / 2.2.22 ( F edora )
Remote addr ess : 10.1 28. 0.2 15
Client brow ser : Moz illa /5.0 ... C hrome /41 .0 .22 72.53 ...
Request me thod :
See http://php.net/manual/en/reserved.variables.server.php
for a list of keys
COMP284 Scripting Languages Lecture 7 Slide L7 8
Available information and Input Form data
Form data
Form data is passed to a PHP script via the three arrays:
$_POST Data from POST client requests
$_GET Data from GET client requests
$_REQUEST Combined data from POST and GET client requests
(derived from $_POST and $_GET)
; Accessing $_REQUEST is the equivalent in PHP to
using cgi.FieldStorage() in a Python CGI program
< form action = ' process . php ' method = ' post ' >
<label > Enter your user name :
< input type = ' text ' name = ' usern ame ' > </ label ><br >
<label > Enter your full name :
< input type = ' text ' name = ' fulln ame ' > </ label ><br >
< input type = ' submit ' value = ' Click for r espo nse ' > </ form >
$_REQUEST['username'] Value entered into field with name ‘username’
$_REQUEST['fullname'] Value entered into field with name ‘fullname’
COMP284 Scripting Languages Lecture 7 Slide L7 9
Available information and Input Form data
Example
We want to develop a PHP script with the following functionality
Access is restricted to IP addresses starting with 138.253
(University of Liverpool IP addresses)
The program prints out an HTML document with an HTML form
that allows a user to enter the data required for our program:
a textfield for entry of a student’s full name
a drop-down menu for selection of the student’s year of registration
The drop-down menu should cover the previous nine years
COMP284 Scripting Languages Lecture 7 Slide L7 10
Available information and Input Form data
Example (continued)
We want to develop a PHP script with the following functionality
On submission of the completed form, the program checks inputs for
validity
If inputs are invalid issues errors messages and prints out the form again
If inputs are valid, (i) generates a username based on the data entered into
that form and (ii) prints out an HTML document with that username
A name is valid if it consists of a single given name and single surname,
each starting with a capital letter followed by one or more lowercase
letters
A year is valid if it consists of four digits
(We have a developed a Python CGI program with the same functionality
in Lecture 2)
COMP284 Scripting Languages Lecture 7 Slide L7 11
Available information and Input Form data
Useful PHP functions
string strtolower(str)
Returns string with all alphabetic characters in str converted to lower-
case
string substr(str, start [, length])
Returns the portion of the string str starting at position start and
consisting of at most length characters
If start is negative, the returned string will start at the start’th
character from the end of string
If length is omitted, the returned string continues til the end of str
string date(format [, timestamp])
Returns a string formatted according to the given format string
format using the given timestamp or the current time if no
timestamp is given
For format ’Y’ returns the current year
COMP284 Scripting Languages Lecture 7 Slide L7 12
Available information and Input Form data
Example: HTML Form
function printF orm () {
echo "
< form action = ' generat e . php ' method = ' post ' >
<label > Enter your full name :
< input type =' text ' name = ' f ulln ame ' >
</ label >
<label > Select your year of r egi str at ion :
< select name = ' year ' required >
< option value = ' ' > - - -- </ option > ";
$now = date ("Y " );
for ( $year = $now - 9; $ year <= $now ; $ year ++)
echo " <option > $year </ option >\ n " ;
echo "
</ select >
</ label >
< input type =' submit ' name = ' s ubmit ' value = ' Gene rate ' >
</ form > ";
}
COMP284 Scripting Languages Lecture 7 Slide L7 13
Available information and Input Form data
Example: Input validation
function va li dat eI npu ts ( $name , $ year ) {
$err = " ";
/* A name is valid if it c onsi sts of a single given name
and single surname , each star ting with a capit al
letter fol lowe d by one or more lowerc ase lette rs */
if (! preg_match ( ' /^[ A -Z ][ a -z ]+\ s +[A - Z ][a - z ]+ $ / ' , $ name ) ) {
$err .= " Please enter your first name f ollo wed by your
, second name . ";
}
/* A year is valid if it c onsi sts of four digi ts */
if (! preg_match ( ' /^\ d {4} $ / ' , $ year ) ) {
$err .= " Pleas e enter the year you r egi ste red using four
, digits ." ;
}
return $ err ;
}
COMP284 Scripting Languages Lecture 7 Slide L7 14
Available information and Input Form data
Example: Username
Simple function for generating a username from the full name of a user
and the year the user has registered
function ge nUs ern ame ( $name , $ year ) {
$names = pre g_s pli t ( ' /\ s +/ ' , $ name );
// first letter of given name
return (" sg " . strtolower ( substr ( $ names [0] , 0 1))
// first three letters of surname
. str tol owe r ( substr ( $ names [1] , 0 , 3))
// last to digits of year
. substr ( $ year , -2) );
}
COMP284 Scripting Languages Lecture 7 Slide L7 15
Available information and Input Form data
Example: Processing inputs
Processing inputs once the user has submitted name and year
function pr ocess Input s ( $name , $ ye ar ) {
if ( $ err = vali dateI nputs ( $name , $ year )) {
/* If the v ali dat ion of in puts p rodu ced a non - empy
error message , show it to the user and prod uce
the form again . */
echo " <div class = ' error ' > $err </ div >\ n";
pri ntForm ();
} else {
/* If the v ali dat ion of in puts p rodu ced an empty
error message , com pute the use rnam e and show
it to the user . */
$us ername = g enU ser name ( $name , $ year );
echo " <div > The user name for $ name re gis ter ed in $year
is $username </ div >\ n ";
}
}
COMP284 Scripting Languages Lecture 7 Slide L7 16
Available information and Input Form data
Example: Putting everything together
<! DOCTYPE html >
< html lang = 'en - GB ' >
<head >
< link rel = ' s tylesheet ' type = ' text / css ' href = ' form . css ' >
<title > Generate Username </ title >
</ head >
<body >
<? php
if ( subs t r ( $ _ S E RV ER [ " REM O T E_ADDR " ] ,0 ,7) != " 138.253 " ) {
echo ( "< div class = ' eror ' ><b > Sorry , plea s e come back
when you are on a uni computer </ b > </ div >\ n " );
} else {
if ( is set ( $ _REQ U E ST [ ' submit ' ])) {
proce s sInput s ( $_REQUES T [ ' fullname ' ] , $ _RE Q U EST [ ' year ' ]);
} else {
// Show user the form
printForm ();
}
}
?>
</ body >
</ html >
COMP284 Scripting Languages Lecture 7 Slide L7 17
Available information and Input Form data
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
COMP284 Scripting Languages Lecture 7 Slide L7 18
Available information and Input Form data
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 " meth od = " post " >
<label > Item : < input type =" text " name = " item " > </ label >
</ form >
form2.php
< form action = " process . php " me thod =" post " >
<label > Address : < input type =" text " name =" addres s " ></ label >
</ form >
process.php
<? php echo $ _RE QUEST [ ' item ' ]; echo $_RE QUES T [ ' address ' ]; ? >
; PHP Notice: Undefined index ’item’
COMP284 Scripting Languages Lecture 7 Slide L7 19
Available information and Input Form data
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 " meth od = " post " >
<label > Item : < input type =" text " name = " item " > </ label >
</ form >
form2.php
< form action = " process . php " me thod =" post " >
<label > Address : < input type =" text " name =" addres s " ></ label >
< input type =" hidden " name = " ' item "
value =" <? php echo $ _REQUES T [' item '] ?> " >
</ form >
process.php
<? php echo $ _RE QUEST [ ' item ' ]; echo $_RE QUES T [ ' address ' ]; ? >
; 'item' is remembered but can be manipulated
COMP284 Scripting Languages Lecture 7 Slide L7 20
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 session can be used
without user authentication, 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
COMP284 Scripting Languages Lecture 7 Slide L7 21
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
COMP284 Scripting Languages Lecture 7 Slide L7 22
PHP sessions
Sessions and cookies
Sessions
ID and session data are stored on the web server (server-side)
Access and changes to session data are done in PHP
via $_SESSION array
Expiration can not be set, session data will be expired when users close
the browser or session is ended by script
Web client / user cannot manipulate the data
Cookies
ID and cookie data are stored by the web client (client-side) on the
user’s device
Access to cookie data is done in PHP via $_COOKIE array
Changes to cookie data are done in PHP via setcookie
Expiration can be set, e.g., via setcookie
Web client / user / hackers can manipulate the data
COMP284 Scripting Languages Lecture 7 Slide L7 23
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()
$_SESSION = array();
void session_unset()
bool setcookie(name, value, expires, path)
COMP284 Scripting Languages Lecture 7 Slide L7 24
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
COMP284 Scripting Languages Lecture 7 Slide L7 25
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 " Sessio n id : " , se ssi on_ id () , " <br > ";
echo " Sessio n name : " , s ess ion_n ame () , " <br >" ;
se ssion _r eg en er ate_id ();
echo " Sessio n id : " , se ssi on_ id () , " <br > "; // changed
echo " Sessio n name : " , s ess ion_n ame () , " <br >" ; // unc hanged
?>
COMP284 Scripting Languages Lecture 7 Slide L7 26
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
COMP284 Scripting Languages Lecture 7 Slide L7 27
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 se ssion
// Each web page conta ins the fol low ing PHP code
ses si on_ start ();
if (! isset ( $ _ SESSION [ ' req uests ' ]))
$_S ESSION [ ' r eque sts '] = 1;
else
$_S ESSION [ ' r eque sts ' ]++;
echo " # Requests in this session so far : " ,
$_S ESSION [ ' r eque sts ']," <br >\ n ";
?>
COMP284 Scripting Languages Lecture 7 Slide L7 28
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
$_SESSION = array() or 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
name: the name of the cookie
value: the value of the cookie
expires: the time the cookie expires (as a Unix timestamp)
path: the path on the server in which the cookie will be available
COMP284 Scripting Languages Lecture 7 Slide L7 29
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
must occur before <html>-tag
<? php
ses si on_ start ();
ses si on_ unset ();
if ( s ess ion _id () != " " || isset ( $ _COO KIE [ sess ion _na me ()]))
// force the cookie to expi re
setcookie ( se ssion _na me () , s ess ion_id () , time () -2592000 , '/ ' );
sessi on_de st roy (); ?>
Note: Closing your web browser will also end a session
COMP284 Scripting Languages Lecture 7 Slide L7 30
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 = " form2 Ses sion . php " me thod =" post " >
<label > Item : < input type =" text " name = " item " > </ label >
</ form >
Starting/maintaining a session for the first form is optional
COMP284 Scripting Languages Lecture 7 Slide L7 31
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 ( $ _ REQ UES T [ ' item ' ]))
$_S ESSI ON [ ' item ' ] = $ _REQUES T [ ' item ' ];
?>
<! D OCTYPE html >
< html lang = ' en - GB ' >
<head > < title > Form 2 </ title > </ head >
<body >
< form action = " pr oce ss Ses si on . php " method = " post " >
<label > Address : < input type =" text " name =" addres s " >
</ label >
<!- - no hidden input req uired -->
</ form >
</ body >
</ html >
COMP284 Scripting Languages Lecture 7 Slide L7 32
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 cessary but co nve nie nt
if ( isset ( $ _ REQ UES T [ ' address ' ]))
$_S ESSI ON [ ' a ddres s ' ] = $ _ REQ UEST [ ' address ' ];
?>
<! D OCTYPE html >
< html lang = ' en - GB ' >
<head > < title > Processing </ title > </ head >
<body >
<? php
echo $ _S ESS ION [ ' item ' ]; echo $ _SESSIO N [ ' address ' ];
// Once we do not need the data anymore , get rid of it
ses si on_ unset (); ses sion_ destr oy ();
?>
</ body > </ html >
COMP284 Scripting Languages Lecture 7 Slide L7 33
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 ( $_ SESS I ON [ ' LAST _ ACTIV I TY ' ]) &&
( t ime () - $_SE S SION [ ' LA S T_AC T I VITY ' ] > 1800 )) {
// last re que st was more than 30 mina tes ago
se s s ion_d e s troy (); // d est roy se ssi on dat a in stor age
$_ S ESS I ON = arr ay (); // unset s ess ion var iabl es
if ( se s sio n _id () != "" || is set ( $ _C OOKI E [ sess i o n_na m e ()]))
se tcoo kie ( se s sion _ n ame () , se s sion _id () , time () -2592000 , ' / ' );
} else {
// upd ate last ac tiv ity tim e stam p
$_ S ESS I ON [ ' LAST_ A CTIV I T Y '] = time ();
}
The following code generates a new session identifier every 30 minutes
if (! i sset ( $_ SESS I ON [ ' CR EATE D ' ])) {
$_ S ESS I ON [ ' CRE ATE D ' ] = time ();
} else if ( time () - $ _ SESS ION [ ' CR EAT ED ' ] > 1800 ) {
// sess ion s tar ted more tha n 30 minates ago
ses s i o n_rege n e r a te_id ( t ru e );
$_ S ESS I ON [ ' CRE ATE D ' ] = time ();
}
http://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session- after- 30-minutes
COMP284 Scripting Languages Lecture 7 Slide L7 34
PHP sessions Example
PHP sessions: Example
mylibrary.php:
<? php
ses si on_ start ();
function d estroy_se ss io n_ an d_ da ta () {
$_S ESSION = array ();
if ( s ess ion _id () != " " || isset ( $ _COO KIE [ sess ion _na me ()]))
setcookie ( se ssion _na me () , s ess ion_id () , time () -2592000 , '/ ' );
sessi on_de st roy ();
}
function co un t_r eq ues ts () {
if (! isset ( $ _ SESSION [ ' req uests ' ]))
$_S ESSION [ ' r eque sts '] = 1;
else $ _S ESS ION [ ' requ ests ' ]++;
return $ _S ESS ION [ ' requests ' ];
}
?>
COMP284 Scripting Languages Lecture 7 Slide L7 35
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 >
Hello vi sito r ! <br > This is your page r equest no " ;
echo co unt_r eques ts (). " from this site . <br >\ n";
echo " <a href = ' page1 . php '> Continue </a > |
<a href = ' finish . 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 >
Good bye visito r ! < br >
<a href = ' page1 . php '> Start again </ a > </ body > ";
?>
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/page1.php
COMP284 Scripting Languages Lecture 7 Slide L7 36
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 () { // unchang ed }
function co un t_r eq ues ts () {
if (! isset ( $ _COOK IE [ ' re quests ' ])) {
set cookie ( ' r eque sts ' , 1, time ()+ 31536000 , ' / ' );
return 1;
} else {
// $ _C OOKIE [' re quests ']++ would not survive , in stea d use
set cookie ( ' r eque sts ' , $ _COOK IE [ ' re quests ' ]+1 ,
time ()+3153 6000 , '/ ' ); // valid for 1 year
return $ _C OOKI E [ ' requests ' ]+1;
} }
?>
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/cpage1.php
COMP284 Scripting Languages Lecture 7 Slide L7 37
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
COMP284 Scripting Languages Lecture 7 Slide L7 38
Authentication Example
PHP Sessions and Authentication: Example
content.php:
<? php
ses si on_ start ();
if (! isset ( $ _ SESSION [ ' user ' ])) {
// User is not logged in , red ire cti ng to login page
header ( ' Locatio n : login . php ' );
}
?>
<! D OCTYPE html >
< html lang = "en - GB " >
<head > < title > Con tent that r equi res login </ title > </ head >
<body >
<h1 > Pr otected Content </ h1 >
<b > We lcome <i > <? php echo $ _S ESS ION [ ' user ' ] ? > </i > </ b >< br >
<b > <a href =" logout . php " > Log Out </a > </ b >
</ body >
</ html >
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/content.php
COMP284 Scripting Languages Lecture 7 Slide L7 39
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 > Us erna me :
< input name =" user " placehol der = " use rnam e " type =" text " >
</ label >
<label > Pa sswo rd :
< input name =" passwd " pl ace hol der = " ** " type = " p assw ord " >
</ label >
< input name =" submit " type = " s ubmit " value = " login " >
<span > <? php echo $ error ; ? > </ span >
</ form >
</ body >
</ html >
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/login.php
COMP284 Scripting Languages Lecture 7 Slide L7 40
Authentication Example
PHP Sessions and Authentication: Example
First part of login.php:
<? php
session_ s t a rt ();
funct i o n c h e c kCreden t i als ( $user , $ p a s s wd ) {
// Ch eck whether $ user and $pass w d are non - e mpty
// and match an entry in the d a t a base
}
$er r or = ' ';
if ( is set ( $ _ S ES S IO N [ ' user ' ])) {
hea der ( " location : content . php " );
} else {
if ( is set ( $ _ R EQ U ES T [ ' su bmit ' ])) {
if ( ch e c k Credent i a ls ( $ _ R EQ U E ST [ ' user ' ] , $ _REQUEST [ ' passwd ' ])) {
$_SESSION [ ' user ' ]= $ _ R E Q U E S T [ ' user ' ];
hea der ( " location : content . php " ); // R e d i recting to Conte n t
} else {
$er r or = " Username or P a s s word is invalid . Try Aga in " ;
} } }
?>
COMP284 Scripting Languages Lecture 7 Slide L7 41
Authentication Example
PHP Sessions and Authentication: Example
logout.php:
<? php
ses si on_ start ();
$user = $ _ SES SION [ ' user ' ];
$_S ESSION = array ();
sessi on_de st roy ();
?>
<! D OCTYPE html >
< html lang = "en - GB " >
<head >
<title > Logout </ title >
</ head >
<body >
<h1 > Logout </ h1 >
<b > Go odbye <i > <? php echo $user ? > </ i > </b > <br >
<b > <a href =" login . php " > Login </ a > </b >
</ form >
</ body >
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/logout.php
COMP284 Scripting Languages Lecture 7 Slide L7 42
Authentication Example
Revision
Read
Chapter 11: Form Handling
Chapter 12: Cookies, Sessions, and Authentication
of
R. Nixon:
Learning PHP, MySQL, and JavaScript.
O’Reilly, 2018.
COMP284 Scripting Languages Lecture 7 Slide L7 43