23
Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

Embed Size (px)

Citation preview

Page 1: Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

Lecture 7Maintaining State (cookies & sessions)

& MySQL Interaction (revisited)

Page 2: Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

Stateful v. Stateless

"State" is a central concern of all sorts of distributed applications, but especially of Web applications. When applied to a protocol, "state" treats each series of interactions as having continuity, much like a single program's state. A "stateless" protocol is one in which there is no such continuity; each request must be processed entirely on its own merits.

•HTTP and its derivatives are intrinsically "stateless".

•The request/response cycle of a HTTP interaction does not maintain "memory" of any previous interactions.

Page 3: Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

Stateful v. Stateless (2)

Stateful Interaction:

Request 1: “What is Alice’s account number?”Response 1: 145678093

Request 2: “What is her current balance?”Response 2: £345.65

Stateless Interaction:

Request 1: “What is Alice’s account number?”Response 1: 145678093

Request 2: “What is Alice’s current balance?”Response 2: £345.65

Page 4: Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

Is PHP stateless? (well … yes)• On a webserver, PHP scripts have no shared state, so

each instance of a PHP script runs in its own logical memory space.

• The scripts maintain no persisted state, so each script start off fresh as a daisy, with no data to indicate what happened the previous times it was executed.

• Variables are destroyed as soon as the page script finishes executing.

• The script can access the ‘referrer’, the address of the previous page, although this can’t really be trusted.

$_SERVER['HTTP_REFERER']

Page 5: Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

Is PHP stateless? (well … not necessarily)

The usual way to maintain state in PHP scripts is via the use of sessions. To understand how these work, we need to have a look at what cookies are and how they work …

Page 6: Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

Client/Server interaction with Cookies

A cookie is a small file that the server embeds on the user's browsers file system. Each time the same browser requests a page, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

Page 7: Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

Setting / Retrieving / Deleting a Cookie with PHP

Setting a cookie : use the setcookie() function setcookie(name, value, expire, path, domain);

Retrieve a cookie : use the $_COOKIE superglobal// Print a cookieecho $_COOKIE["name"];

// A way to view all cookiesprint_r($_COOKIE);

Delete a cookie : set the time to a past instance // set the expiration date to one hour ago

setcookie("name", "", time()-3600);

Page 8: Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

<?php if (!isset($_COOKIE['visits'])) $_COOKIE['visits'] = 0; $visits = $_COOKIE['visits'] + 1; setcookie('visits', $visits, time()+3600*24*365);?><html><head> <title> Title </title></head><body><?php if ($visits > 1) { echo("This is visit number $visits."); } else { // First visit echo('Welcome to my Website! This is your first visit!'); }?></body></html>

Note : the cookie must be sent before any other headers.

Setting & Retrieving a Cookie with PHP

Run it

Page 9: Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

setcookie(name [,value [,expire [,path [,domain,secure]]]]])

name = cookie name

value = data to store (string)

expire = UNIX timestamp when the cookie expires. Default is that cookie expires when browser is closed.

path = Path on the server within and below which the cookie is available on.

domain = Domain at which the cookie is available for.

secure = If cookie should be sent over HTTPS connection only. Default false.

setcookie() keys & values

Page 10: Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

• Each cookie on the user’s computer is connected to a particular domain.

• Each cookie can store up to 4kB of data.• A maximum of 20 cookies can be stored on a user’s PC per

domain• Only strings can be stored in Cookie files.• To store an array in a cookie, convert it to a string by using

the serialize() PHP function. • The array can be reconstructed using the unserialize() function once it had been read back in.

• Cookies are stored client-side, so never can’t be trusted completely: They can be easily viewed, modified or created by a 3rd party.

• They can be turned on and off at will by the user.

Cookie limits & notes

Page 11: Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

PHP Sessions

• Since HTTP is a stateless protocol – a PHP session can be used to store user information on the server for later use (i.e. username, shopping items, etc).

• Session information is temporary and will be deleted after the user has left the website. Session data can be made persistent by storing the data in a database.

• Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL (if cookies are turned off for instance).

Page 12: Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

Cookies Sessions

Limited storage space Practically unlimited space

Insecure storage client-side Reasonably securely stored server-side

User controlled No user control

Cookies v. Sessions

Page 13: Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

session_start();

PHP does all the work: It looks for a valid session id in the $_COOKIE or $_GET superglobals – if found it initializes the data. If none found, a new session id is created. Note that like setcookie(), this function must be called before any echoed output to browser.

Example session id:26fe536a534d3c7cde4297abb45e275a

Starting / Resuming a Session

Page 14: Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

The $_SESSION superglobal array can be used to store any session data.

e.g. $_SESSION[‘name’] = $name;$_SESSION[‘age’] = $age;

To retrieve session values, data is simply read back from the $_SESSION superglobal array.

e.g. $name = $_SESSION[‘name’];$age = $_SESSION[‘age’];

To delete session data – simply unset()a particular session variable

e.g. unset($_SESSION[‘name’]);

To destroy a session – use the session_destory() functione.g. session_destory();

Storing / Retrieving / Deleting Session data

Page 15: Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

Setting & Retrieving a Session value with PHP

<?phpsession_start();

if(isset($_SESSION['visits'])) {$_SESSION['visits']=$_SESSION['visits']+1;

}else {

$_SESSION['visits']=1;}echo "This is visit number ". $_SESSION['visits'];?>

Run it

Page 16: Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

Typical process flow to save session data in a DB

Page 17: Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

PHP & DB Interaction with MySQL

• Open Source (relational) database serverRuns on many platforms (Unix & Windows)

• Networked server – no fancy GUI like MS Access.You can find clients (such as phpMyAdmin) that provide a GUI. phpMyAdmin @ cems : http://isa.cems.uwe.ac.uk/phpmyadmin (note: only available within uwe)

• Great for small, medium to large-sized applications (ebay, amazon, facebook etc. all make use of it)

MySQL

Page 18: Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

phpMyAdmin

• A MySQL client written in PHP

• Via a browser you can manage:• Manage Databases• Manage MySQL users• Submit queries (SQL)

• A great way to learn SQL!

Page 19: Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

There are three main API options when considering connecting to a MySQL database server: •PHP's MySQL Extension - original extension which provides a procedural interface and is intended for use only with MySQL versions older than 4.1.3. Can be used with versions of MySQL 4.1.3 or newer, but not all of the latest MySQL server features will be available. •PHP's mysqli Extension - MySQL improved extension takes advantage of new features found in MySQL versions 4.1.3 and newer. The mysqli extension is included with PHP versions 5 and later. •PHP Data Objects (PDO) - PHP Data Objects, or PDO, is a database abstraction layer that provides a consistent API regardless of the type of database server. In theory, it allows for the switch of the database server, from say Firebird to MySQL, with only minor changes the PHP code.

PHP (main) API’s for using MySQL

Page 20: Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

Advantages of the mysqli API

• Object-oriented interface

• Support for Prepared Statements

• Support for Multiple Statements

• Support for Transactions

• Enhanced debugging capabilities

• Embedded server support

Note: If using MySQL versions 4.1.3 or later it is strongly recommended that the mysqli extension is used.

Page 21: Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

qid quote author dob dod url category

1 There is no remedy but to love more.

Henry David Thoreau

1817 1862 http://en.wikipedia.org/wiki/Henry_David_Thoreau

love

6 Work is the curse of the drinking classes.

Oscar Wilde 1854 1900 http://en.wikipedia.org/wiki/Oscar_wilde

humour

11 Religion is what keeps the poor from murdering the rich.

Napoleon Bonaparte

1769 1821 http://en.wikipedia.org/wiki/Napoleon

politics

example MySQL db

Entity Model

Example records (3)

Page 22: Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

// Connect to the db$mysqli = new mysqli('hostname','username','password','database');

//Send the query to the database and pull the records in a // certain category using the SELECT statement // If the result returns trueif ($result = $mysqli->query("SELECT quote, url FROM quote

WHERE category='love'")) {

// print out the number of records retrievedecho 'For the category "love", there are '

.$result->num_rows.' records.<br/>';

// The "fetch_object()" method allows access to the returned // rows within the resource object ($result in this case). while ($row = $result->fetch_object()) {

echo 'Quote: '.$row->quote.' ';echo 'URL: <a href='.$row->url.'>'.$row->url.

'</a><br/>';}

} else { // it’s an error & the query failed

echo $mysqli->error; } // end else $mysqli->close();

example script using mysqli

Run it

Page 23: Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

Update / delete/ add new record using mysqli –left as an exercise