Presentation is loading. Please wait.

Presentation is loading. Please wait.

UFCE8V-20-3 Information Systems Development 3 (SHAPE HK)

Similar presentations

Presentation on theme: "UFCE8V-20-3 Information Systems Development 3 (SHAPE HK)"— Presentation transcript:

1 UFCE8V-20-3 Information Systems Development 3 (SHAPE HK)
Lecture 4 PHP (3) : Maintaining State – Cookies & Sessions

2 last lecture … Inbuilt functions Common inbuilt function examples
User defined functions - declaration - return statement - values & references - scope (local & global) - arguments - default values Environment Variables & Superglobals $_GET & $_POST

3 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.

4 Stateful v. Stateless (2)
Stateful Interaction: Request 1: “What is Alice’s account number?” Response 1: Request 2: “What is her current balance?” Response 2: £345.65 Stateless Interaction: Request 1: “What is Alice’s account number?” Response 1: Request 2: “What is Alice’s current balance?” Response 2: £345.65

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']

6 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 …

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

8 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 cookie echo $_COOKIE["name"]; // A way to view all cookies print_r($_COOKIE); Delete a cookie : set the time to a past instance // set the expiration date to one hour ago setcookie("name", "", time()-3600);

9 Setting & Retrieving a Cookie with PHP
if (!isset($_COOKIE['visits'])) $_COOKIE['visits'] = 0; $visits = $_COOKIE['visits'] + 1; setcookie('visits', $visits, time()+3600*24*365); ?> <!DOCTYPE html> <html> <head> <title>PHP Cookie Example 1</title> </head> <body> if ($visits > 1) { echo("This is visit number $visits."); } else { #First visit echo('Welcome to my Website! This is your first visit!'); </body> </html> read cookie value to variable, add 1 set cookie to now + 1 year run script ** Note : the cookie must be sent before any other headers. Keep refreshing the page to see the cookie at work.

10 setcookie() keys & values
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.

11 Cookie limits & notes 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.

12 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).

13 Cookies v. Sessions Cookies Sessions Limited storage space
Practically unlimited space Insecure storage client-side Reasonably securely stored server-side User controlled No user control

14 Starting / Resuming a Session
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

15 Storing / Retrieving / Deleting Session data
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. $name = $_SESSION[‘name’]; $age = $_SESSION[‘age’]; To delete session data – simply unset()a particular session variable unset($_SESSION[‘name’]); To destroy a session – use the session_destory() function e.g. session_destory();

16 Setting & Retrieving a Session value with PHP
<?php session_start(); if(isset($_SESSION['visits'])) { $_SESSION['visits']=$_SESSION['visits']+1; } else { $_SESSION['visits']=1; } echo "This is visit number ". $_SESSION['visits']; ?> must be the first line in script ** Note : Keep refreshing the page to see the session counter at work. run script

17 Typical process flow to save session data in a DB

Download ppt "UFCE8V-20-3 Information Systems Development 3 (SHAPE HK)"

Similar presentations

Ads by Google