Advanced IP-Chapter-5 - Lect-11-PHP Cookies & Sessions
Advanced IP-Chapter-5 - Lect-11-PHP Cookies & Sessions
1
The need for persistence
Consider these examples
Counting the number of “hits” on a website
i.e. how many times does a client load your web
page source
The questionnaire on computing experience
2
Persistence
Persistence is the ability of data to outlive the
execution of the program that created them.
3
Persistence and HTTP
Recall http is a stateless protocol. It remembers nothing about
previous transfers
HTTP
Client server
Session
Cookie
4
Cookies v. Sessions
Cookies Sessions
Limited storage space Practically unlimited space
The NAME value is a URL-encoded name that identifies the
cookie.
The PATH and DOMAIN specify where the cookie applies
7
setcookie(name,value,expire,path,domain,secure)
Parameter Description
Name (Required). Specifies the name of the cookie
Value (Required). Specifies the value of the cookie
Expire (Optional). Specifies when the cookie expires.
e.g. time()+3600*24*30 will set the cookie to expire in 30 days.
If this parameter is not set, the cookie will expire at the end of the session (when the browser
closes).
If set to "/", the cookie will be available within the entire domain.
If set to "/phptest/", the cookie will only be available within the test directory and all sub-
directories of phptest.
The default value is the current directory that the cookie is being set in.
Secure (Optional). Specifies whether or not the cookie should only be transmitted over a secure
HTTPS connection.
TRUE indicates that the cookie will only be set if a secure connection exists. Default is
FALSE. 8
Cookies from HTTP
9
How to Create a Cookie
<?php
header(“Set-Cookie: mycookie=myvalue; path=/;
domain=.coggeshall.org”);
?>
11
Creating cookies with setcookie()
Use the PHP setcookie() function:
Setcookie (name,value,expire, path, domain, secure)
e.g.
<?php
setcookie("MyCookie", $value, time()+3600*24);
setcookie("AnotherCookie", $value, time()+3600);
?>
Name: name of the file
Value: data stored in the file
Expire: data string defining the life time
Path: subset of URLs in a domain where it is valid
Domain: domain for which the cookie is valid
Secure: set to '1' to transmit in HTTPS 12
Reading cookies
To access a cookie received from a client, use the PHP
$_COOKIE superglobal array
<?php
?>
<?php
foreach ($_COOKIE as $key=>$val) {
print $key . " => " . $val . "<br/>";
}
?>
Gets an error!:
Warning: Cannot modify header information - headers already sent by (output started at
/var/www/html/TESTandre/159339/PHP/cookie_with_headers.php:9) in
/var/www/html/TESTandre/159339/PHP/cookie_with_headers.php on line 11
15
Using headers
16
Using headers (correct approach)
<?php
$strValue = "This is my first cookie";
setcookie ("mycookie", $strValue);
echo "Cookie set<br>";
?>
17
This is the correct approach!
Deleting a cookie
Set the cookie with its name only:
setcookie(“mycookie”);
18
Multiple data items
Use explode() e.g.
<?php
$strAddress = $_SERVER['REMOTE_ADDR'];
$strBrowser = $_SERVER['HTTP_USER_AGENT'];
$strOperatingSystem = $_ENV['OS'];
$strInfo = "$strAddress::$strBrowser::$strOperatingSystem";
setcookie ("somecookie4",$strInfo, time()+7200);
?>
<?php
$strReadCookie = $_COOKIE["somecookie4"];
$arrListOfStrings = explode ("::", $strReadCookie);
echo "<p>$strInfo</p>";
echo "<p>Your IP address is: $arrListOfStrings[0] </p>";
echo "<p>Client Browser is: $arrListOfStrings[1] </p>";
echo "<p>Your OS is: $arrListOfStrings[2] </p>"; 19
?>
Where is the cookie stored?
20
Where is the cookie stored
Depends on the browser...
e.g., firefox/mozilla under /home/a________
Look for cookies.txt in .mozilla directory
Usually under:
/home/a______/.mozilla/firefox/asdkfljy.default
Cookie is stored only if there is an expiry date
Otherwise it is deleted when leaving browser
Persistent only if an expiry date is set
21
PHP Sessions
You can store user information (e.g. username, items
selected, etc.) in the server side for later use using PHP
session.
22
When should you use sessions?
Need for data to stored on the server
Unique session information for each user
Transient data, only relevant for short time
Data does not contain secret information
Similar to Cookies, but it is stored on the server
More secure, once established, no data is sent back and forth
between the machines
Works even if cookies are disabled
Example: we want to count the number of “hits” on our
web page.
23
Before you can store user information in your PHP session,
you must first start up the session.
<html>
<body>
</body>
</html>
24
PHP Sessions
Starting a PHP session:
<?php
session_start();
?>
sess_f1234781237468123768asjkhfa7891234g
25
How to Retrieve a Session Value
Register Session variable
session_register('var1','var2',...); // will also create a session
PS:Session variable will be created on using even if you will
not register it!
Use it
<?php
session_start();
if (!isset($_SESSION['count']))
$_SESSION['count'] = 0;
else
$_SESSION['count']++;
?>
Session variables
$_SESSION
e.g., $_SESSION[“intVar”] = 10;
27
Registering session variables
Instead of setting superglobals, one can register one’s own
session variables
<?php
$barney = “A big purple dinosaur.”;
$myvar_name = “barney”;
session_register($myvar_name);
?>
With session_start() a default session variable is
created - the name extracted from the page name
To create your own session variable just add a new key
to the $_SESSION superglobal
29
Session Example 1
<?php
session_start();
if (!isset($_SESSION["intVar"]) ){
$_SESSION["intVar"] = 1;
} else {
$_SESSION["intVar"]++;
}
echo "<p>In this session you have accessed this page " .
$_SESSION["intVar"] . "times.</p>";
?>
30
Session Example 2
<?php session_start();?>
<?php
$thisPage = $_SERVER['PHP_SELF'];
if (!isset($_SESSION[$sessionName])) {
$_SESSION[$sessionName] = 0;
print "This is the first time you have visited this page<br/>";
}
else {
$_SESSION[$sessionName]++;
}
print "<h1>You have visited this page " . $_SESSION[$sessionName] .
" times</h1>"; 31
?>
Ending sessions
unset($_SESSION[‘name’])
–Remove a session variable
session_destroy()
– Destroys all data registered to a session
– Does not unset session global variables and cookies
associated with the session
–Not normally done - leave to timeout
32
Destroying a session completely
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) { // Returns the value of the configuration option
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
returns the name of the
current session
// Finally, destroy the session.
session_destroy();
?>
33
Session Example 3
<?php
session_start();
if(isset($_POST["submit"]) ) {
$strColourBg = $_POST["strNewBg"];
$strColourFg = $_POST["strNewFg"];
$_SESSION['strColourBg'] = $strColourBg;
$_SESSION['strColourFg'] = $strColourFg;
echo "<br>New Settings";
}
else {
$strColourBg = $_SESSION['strColourBg'];
$strColourFg = $_SESSION['strColourFg'];
echo "<br>Keep old settings";
34
}
?>
Session Example 3 (cont.)
<head> <style type="text/css">
body {background-color: <?php echo $strColourBg ?>}
p {color: <?php echo $strColourFg?>}
h2 {color: <?php echo $strColourFg?>}
</style></head>
<body>
<h2>h2 colour</h2>
<form action = '<?php echo $SERVER["PHP_SELF"] ?>' method='post'>
<label for="strNewBg"> Background colour: </label>
<select name='strNewBg' id='strNewBg'>
<option>red</option> ... <option>grey</option>
</select>
<label for="strNewFg"> Text colour: </label>
<select name='strNewFg' id='strNewFg'>
<option>yellow</option> ... <option>grey</option>
</select>
<input type='submit' name='submit'/>
35
</form></body>