comp284 scripting languages - handoutscgi.csc.liv.ac.uk/~ullrich/comp284/notes/lect07.pdf1 web...

44
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

Upload: others

Post on 25-Sep-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

COMP284 Scripting LanguagesLecture 7: PHP (Part 5)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 2: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

Contents1 Web applications

OverviewHTML forms

2 Available information and InputOverviewPHP environmentServer variablesForm data

3 PHP sessionsStart a PHP sessionMaintain session dataEnd a PHP sessionSession managementExample

4 AuthenticationOverviewExample

COMP284 Scripting Languages Lecture 7 Slide L7 – 1

Page 3: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

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

Page 4: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

Web applications HTML forms

HTML forms

When considering Pythan CGI programming we have used HTML formsthat generated a client request that was handled by a Python CGIprogram:

<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 webserver, for example $HOME/public_html, and be readable by the webserver

• The PHP script file name must have the extension .php, e.g. demo.php

COMP284 Scripting Languages Lecture 7 Slide L7 – 3

Page 5: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

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 secondssince January 1 1970 00:00:00 GMT

COMP284 Scripting Languages Lecture 7 Slide L7 – 4

Page 6: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

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 informationINFO_GENERAL The configuration, php.ini location, build

date, web serverINFO_CONFIGURATION Local and master values for PHP directivesINFO_MODULES Loaded modulesINFO_VARIABLES All EGPCS data

<html lang='en-GB'><head ></head ><body ><?php

phpinfo (); // Show all information

phpinfo(INFO_VARIABLES ); // 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

Page 7: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

Available information and Input PHP environment

Manipulating the PHP configuration

The following functions can be used to access and change theconfiguation 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’sexecution 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

Page 8: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

Available information and Input PHP environment

Manipulating the PHP configuration: Debugging

• By default, our web server does not make errors, notices, and warningsvisible 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 isreported by PHP

<html lang='en-GB'><head ></head ><body ><?php

ini_set('display_errors ' ,1);error_reporting(E_ALL | E_STRICT );

echo '<p>The value of 1 divided by 0 is ' ,1/0,'</p>';?>

</body ></html >

COMP284 Scripting Languages Lecture 7 Slide L7 – 7

Page 9: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

Available information and Input Server variables

Server variables

The $_SERVER array stores information about the web serverand the client request

; Corresponds to os.environ array in Python CGI programs

<html lang='en-GB'><head ></head ><body ><?php

echo 'Server software: ',$_SERVER['SERVER_SOFTWARE '],'<br>';echo 'Remote address: ',$_SERVER['REMOTE_ADDR '], '<br >';echo 'Client browser: ',$_SERVER['HTTP_USER_AGENT '],'<br>';echo 'Request method: ',$_SERVER['REQUEST_METHOD '];?></body ></html >

https://cgi.csc.liv.ac.uk/~ullrich/COMP284/examples/server.php

Server software: Apache /2.2.22 (Fedora)

Remote address: 10.128.0.215

Client browser: Mozilla /5.0 ... Chrome /41.0.2272.53 ...

Request method:

See http://php.net/manual/en/reserved.variables.server.php

for a list of keysCOMP284 Scripting Languages Lecture 7 Slide L7 – 8

Page 10: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

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 tousing cgi.FieldStorage() in a Python CGI program

<form action='process.php' method='post'><label >Enter your user name:

<input type='text' name='username '></label ><br><label >Enter your full name:

<input type='text' name='fullname '></label ><br><input type='submit ' value='Click for response '></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

Page 11: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

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 formthat 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

Page 12: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

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 intothat 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 lowercaseletters

• A year is valid if it consists of four digits

(We have a developed a Python CGI program with the same functionalityin Lecture 2)

COMP284 Scripting Languages Lecture 7 Slide L7 – 11

Page 13: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

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 andconsisting 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 stringformat using the given timestamp or the current time if notimestamp is given

• For format ’Y’ returns the current year

COMP284 Scripting Languages Lecture 7 Slide L7 – 12

Page 14: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

Available information and Input Form data

Example: HTML Form

function printForm () {

echo "

<form action='generate.php' method='post '><label >Enter your full name:

<input type='text' name='fullname '></label >

<label >Select your year of registration:

<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='submit ' value='Generate '></form >";

}

COMP284 Scripting Languages Lecture 7 Slide L7 – 13

Page 15: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

Available information and Input Form data

Example: Input validation

function validateInputs($name ,$year) {

$err = "";

/* 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 */

if (! preg_match('/^[A-Z][a-z]+\s+[A-Z][a-z]+$/',$name)) {

$err .= "Please enter your first name followed by your

↪→second name.";

}

/* A year is valid if it consists of four digits */

if (! preg_match('/^\d{4}$/',$year)) {

$err .= "Please enter the year you registered using four

↪→ digits.";

}

return $err;}

COMP284 Scripting Languages Lecture 7 Slide L7 – 14

Page 16: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

Available information and Input Form data

Example: Username

Simple function for generating a username from the full name of a userand the year the user has registered

function genUsername($name ,$year) {

$names = preg_split('/\s+/',$name);// first letter of given name

return ("sg" . strtolower(substr($names [0], 0 1))

// first three letters of surname

. strtolower(substr($names [1], 0, 3))

// last to digits of year

. substr($year , -2) );

}

COMP284 Scripting Languages Lecture 7 Slide L7 – 15

Page 17: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

Available information and Input Form data

Example: Processing inputs

Processing inputs once the user has submitted name and year

function processInputs($name ,$year) {

if ($err = validateInputs($name ,$year)) {

/* If the validation of inputs produced a non -empy

error message , show it to the user and produce

the form again. */

echo "<div class='error '>$err </div >\n";printForm ();

} else {

/* If the validation of inputs produced an empty

error message , compute the username and show

it to the user. */

$username = genUsername($name ,$year);echo "<div >The user name for $name registered in $year

is $username </div >\n";}

}

COMP284 Scripting Languages Lecture 7 Slide L7 – 16

Page 18: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

Available information and Input Form data

Example: Putting everything together

<!DOCTYPE html >

<html lang='en-GB'><head >

<link rel='stylesheet ' type='text/css' href='form.css'><title >Generate Username </title >

</head >

<body >

<?php

if (substr($_SERVER["REMOTE_ADDR"],0,7) != "138.253") {

echo("<div class='eror '><b>Sorry , please come back

when you are on a uni computer </b></div >\n");

} else {

if (isset($_REQUEST['submit '])) {

processInputs($_REQUEST['fullname '],$_REQUEST['year ']);} else {

// Show user the form

printForm ();

}

}

?>

</body >

</html >

COMP284 Scripting Languages Lecture 7 Slide L7 – 17

Page 19: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

Available information and Input Form data

Web Applications Revisited

SelectItem

EnterAddress

EnterPayment

ConfirmOrder

App

App

App

App

App

Request

Response

Request

Response

Request

Response

Request

Response

Request

• An interaction between a userand a server-side web applicationoften requires a sequence ofrequests and responses• For each request, the application

starts from scratch• it does not remember any data

between consecutive requests

• it does not know whether therequests come from the same useror different users

; data needs to be transferredfrom one execution of theapplication to the next

COMP284 Scripting Languages Lecture 7 Slide L7 – 18

Page 20: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

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 intothe 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="address" ></label >

</form >

process.php<?php echo $_REQUEST['item']; echo $_REQUEST['address ']; ?>

; PHP Notice: Undefined index ’item’

COMP284 Scripting Languages Lecture 7 Slide L7 – 19

Page 21: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

Available information and Input Form data

Transfer of Data: Hidden Inputs

• Assume for a sequence of requests we do not care whether they comefrom 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="address" ></label >

<input type="hidden" name="'item"value="<?php echo $_REQUEST['item '] ?>">

</form >

process.php<?php echo $_REQUEST['item']; echo $_REQUEST['address ']; ?>

; 'item' is remembered but can be manipulatedCOMP284 Scripting Languages Lecture 7 Slide L7 – 20

Page 22: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

PHP sessions

Sessions

• Assume for a sequence of requests we do care that they come from thesame user and that remembered data has not been manipulated

• Sessions help to solve this problem by associating client requests with aspecific user and maintaining data over a sequence of requests fromthat user

• Sessions are often linked to user authentication but session can be usedwithout user authentication, for example, eCommerce websites maintaina ‘shopping basket’ without requiring user authentication first

However, sessions are the mechanism that is typically used to allow ordeny access to web pages based on a user having been authenticated

COMP284 Scripting Languages Lecture 7 Slide L7 – 21

Page 23: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

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 informationthat 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 adatabase to store such information

COMP284 Scripting Languages Lecture 7 Slide L7 – 22

Page 24: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

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 PHPvia $_SESSION array

• Expiration can not be set, session data will be expired when users closethe 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 theuser’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

Page 25: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

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

Page 26: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

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

Page 27: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

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 sessionbeing ‘hijacked’

<?php

session_start ();

echo "Session id: ",session_id (),"<br>";

echo "Session name: ",session_name (),"<br>";

session_regenerate_id ();

echo "Session id: ",session_id (),"<br>"; // changed

echo "Session name: ",session_name (),"<br>"; // unchanged

?>

COMP284 Scripting Languages Lecture 7 Slide L7 – 26

Page 28: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

PHP sessions Maintain session data

Maintain session data

bool session_start()

• resumes the current session based on a session identifierpassed 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 callsor 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

Page 29: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

PHP sessions Maintain session data

Maintain session data

bool session_start()

$_SESSION array

bool isset($_SESSION[key])

<?php

// Counting the number of page requests in a session

// Each web page contains the following PHP code

session_start ();

if (! isset($_SESSION['requests ']))$_SESSION['requests '] = 1;

else

$_SESSION['requests ']++;echo "#Requests in this session so far: ",

$_SESSION['requests '],"<br >\n";?>

COMP284 Scripting Languages Lecture 7 Slide L7 – 28

Page 30: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

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 cookievalue: the value of the cookieexpires: 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

Page 31: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

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

session_start ();

session_unset ();

if (session_id () != "" || isset($_COOKIE[session_name ()]))// force the cookie to expire

setcookie(session_name (), session_id (),time () -2592000 ,'/');session_destroy (); ?>

Note: Closing your web browser will also end a session

COMP284 Scripting Languages Lecture 7 Slide L7 – 30

Page 32: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

PHP sessions End a PHP session

Transfer of Data: Sessions (Part 1)

• Assume for a sequence of requests we do care whether they come fromthe same user or different users

form1Session.php (no changes)

<form action="form2Session.php" method="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

Page 33: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

PHP sessions End a PHP session

Transfer of Data: Sessions (Part 2)

• Assume for a sequence of requests we do care whether they come fromthe same user or different users

form2Session.php

<?php

session_start ();

if (isset($_REQUEST['item']))$_SESSION['item'] = $_REQUEST['item'];

?>

<!DOCTYPE html >

<html lang='en-GB'><head ><title >Form 2</title ></head >

<body >

<form action="processSession.php" method="post">

<label >Address: <input type="text" name="address">

</label >

<!-- no hidden input required -->

</form >

</body >

</html >

COMP284 Scripting Languages Lecture 7 Slide L7 – 32

Page 34: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

PHP sessions End a PHP session

Transfer of Data: Sessions (Part 3)

• Assume for a sequence of requests we do care whether they come fromthe same user or different users

processSession.php

<?php

session_start ();

// not necessary but convenient

if (isset($_REQUEST['address ']))$_SESSION['address '] = $_REQUEST['address '];

?>

<!DOCTYPE html >

<html lang='en-GB'><head ><title >Processing </title ></head >

<body >

<?php

echo $_SESSION['item']; echo $_SESSION['address '];// Once we do not need the data anymore , get rid of it

session_unset (); session_destroy ();

?>

</body ></html >

COMP284 Scripting Languages Lecture 7 Slide L7 – 33

Page 35: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

PHP sessions Session management

More on session management

The following code tracks whether a session is active and ends the sessionif there has been no activity for more then 30 minutesif (isset($_SESSION['LAST_ACTIVITY ']) &&

(time() - $_SESSION['LAST_ACTIVITY '] > 1800)) {

// last request was more than 30 minates ago

session_destroy (); // destroy session data in storage

$_SESSION = array (); // unset session variables

if (session_id () != "" || isset($_COOKIE[session_name ()]))setcookie(session_name (), session_id (),time () -2592000 , '/');

} else {

// update last activity time stamp

$_SESSION['LAST_ACTIVITY '] = time ();

}

The following code generates a new session identifier every 30 minutes

if (! isset($_SESSION['CREATED '])) {

$_SESSION['CREATED '] = time ();

} else if (time() - $_SESSION['CREATED '] > 1800) {

// session started more than 30 minates ago

session_regenerate_id(true);

$_SESSION['CREATED '] = time ();

}

http://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes

COMP284 Scripting Languages Lecture 7 Slide L7 – 34

Page 36: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

PHP sessions Example

PHP sessions: Example

mylibrary.php:<?php

session_start ();

function destroy_session_and_data () {

$_SESSION = array ();

if (session_id () != "" || isset($_COOKIE[session_name ()]))setcookie(session_name (), session_id (),time () -2592000 ,'/');

session_destroy ();

}

function count_requests () {

if (! isset($_SESSION['requests ']))$_SESSION['requests '] = 1;

else $_SESSION['requests ']++;return $_SESSION['requests '];

}

?>

COMP284 Scripting Languages Lecture 7 Slide L7 – 35

Page 37: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

PHP sessions Example

PHP sessions: Example

page1.php:<?php

require_once 'mylibrary.php';echo "<html lang='en -GB '><head ></head ><body >

Hello visitor!<br >This is your page request no ";

echo count_requests ()." from this site.<br >\n";

echo "<a href='page1.php '>Continue </a> |

<a href='finish.php '>Finish </a></body >";?>

finish.php:<?php

require_once 'mylibrary.php';destroy_session_and_data ();

echo "<html lang='en -GB '><head ></head ><body >Goodbye visitor!<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

Page 38: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

PHP sessions Example

PHP and Cookies

Cookies can survive a session and transfer information from one session tothe next

cmylibrary.php:<?php

session_start ();

function destroy_session_and_data () { // unchanged }

function count_requests () {

if (!isset($_COOKIE['requests '])) {

setcookie('requests ', 1, time ()+31536000 , '/');return 1;

} else {

// $_COOKIE['requests ']++ would not survive , instead use

setcookie('requests ', $_COOKIE['requests ']+1,time ()+31536000 , '/'); // valid for 1 year

return $_COOKIE['requests ']+1;} }

?>

https://cgi.csc.liv.ac.uk/~ullrich/COMP284/examples/cpage1.php

COMP284 Scripting Languages Lecture 7 Slide L7 – 37

Page 39: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

Authentication Overview

PHP Sessions and Authentication

• Sessions are the mechanism that is typically used to allow or denyaccess 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 authenticatethemselves by providing a username and password on the page login.php

• The system maintains a list of valid usernames and passwords in a databaseand checks usernames and passwords entered by the user against thatdatabaseIf the check succeeds, a session variable is set

• The page content.php checks whether this session variable is setIf the session variable is set, the user will see the content of the pageIf 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 outagain

COMP284 Scripting Languages Lecture 7 Slide L7 – 38

Page 40: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

Authentication Example

PHP Sessions and Authentication: Example

content.php:<?php

session_start ();

if (! isset($_SESSION['user'])) {

// User is not logged in, redirecting to login page

header('Location:login.php');}

?>

<!DOCTYPE html >

<html lang="en -GB">

<head ><title >Content that requires login </title ></head >

<body >

<h1 >Protected Content </h1>

<b>Welcome <i><?php echo $_SESSION['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

Page 41: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

Authentication Example

PHP Sessions and Authentication: Example

Second part of login.php:<!DOCTYPE html >

<html lang="en -GB">

<head ><title >Login </title ></head >

<body >

<h1 >Login </h1>

<form action="" method="post">

<label >Username:

<input name="user" placeholder="username" type="text">

</label >

<label >Password:

<input name="passwd" placeholder="**" type="password">

</label >

<input name="submit" type="submit" 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

Page 42: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

Authentication Example

PHP Sessions and Authentication: Example

First part of login.php:

<?php

session_start ();

function checkCredentials($user ,$passwd) {

// Check whether $user and $passwd are non -empty

// and match an entry in the database

}

$error='';if (isset($_SESSION['user '])) {

header("location:content.php");

} else {

if (isset($_REQUEST['submit '])) {

if (checkCredentials($_REQUEST['user '],$_REQUEST['passwd '])) {

$_SESSION['user ']= $_REQUEST['user '];header("location:content.php"); // Redirecting to Content

} else {

$error = "Username or Password is invalid. Try Again";

} } }

?>

COMP284 Scripting Languages Lecture 7 Slide L7 – 41

Page 43: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

Authentication Example

PHP Sessions and Authentication: Example

logout.php:<?php

session_start ();

$user = $_SESSION['user'];$_SESSION = array ();

session_destroy ();

?>

<!DOCTYPE html >

<html lang="en -GB">

<head >

<title >Logout </title >

</head >

<body >

<h1 >Logout </h1 >

<b>Goodbye <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

Page 44: COMP284 Scripting Languages - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP284/notes/lect07.pdf1 Web applications Overview HTML forms 2 Available information and Input Overview PHP environment

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