SlideShare a Scribd company logo
PHP
Cookies and Sessions
COMP 2021
Unix and Script Programming
HTTP - a ‘Stateless’ Environment
stateless
(adj.) Having no information about what occurred previously.
 HTTP is stateless – it does not keep track of the client
between requests
 When you browse the web, you are not always connected to the
server
 Once the request has been processed and returned from the server,
the connection is closed
 Connection needs to be re-opened when you need new information
or refresh
Cookies and Sessions
 But sometimes we need to keep track of information, or have
persistent data
 Shopping cart
 “Remember me” on login sites
 PHP sessions and cookies are mechanisms for introducing
state into HTTP transactions.
 Cookies – small file stored client-side
 Sessions – relevant data stored on the server
HTTP
server
Client
Cookie
Session
Is PHP Stateless?
 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']
 It is possible to add data to a database/text file to add
persistent data, although this is not connected with a
particular user…
Cookies
What is a Cookie?
 HTTP cookies are data which a server-side script sends
to a web client to keep for a period of time.
 a small text file that is stored on a user’s computer
 On every subsequent HTTP request, the web client
automatically sends the cookies back to server (unless
the cookie support is turned off).
 The cookies are embedded in the HTTP header (and
therefore not visible to the users).
How do HTTP Cookies work?
Cookies are transferred between server and client according to
HTTP
1. User sends a HTTP request for page for the first time.
2. Server sends back the HTTP response (e.g. HTML webpage) to
the browser AND stores some data in a cookie on the user’s PC.
3. At the next page request, all cookie data associated with this
domain is sent too.
Cookie Fact
 Cookies are sent from the server to the client via “Set-
Cookie” headers
 Set-Cookie: NAME=VALUE; expires=DATE; path=PATH;
domain=DOMAIN_NAME; secure
 Each cookie on the user’s computer is connected to a
particular domain.
 Each cookie be used to store up to 4kB of data.
 A maximum number of cookies can be stored on a user’s
PC per domain is browser dependent
 Usually a few tens
 Cookies can be created with JavaScript
or PHP
elearning.strathmore.edu
apps.strathmore.edu
attachment.strathmore.edu
.strathmore.edu
The USER is in Control
 Cookies are stored client-side
 Cookie is stored (or persistent) only if there is an expiry date
 Otherwise it is deleted when leaving browser
 They can be turned on and off at will by the user
 Never trust them completely: they can be easily viewed,
modified or created by a 3rd party
 Exact location depends on browser, e.g. IE cookies
Example: Default IE Cookie Setting
Create PHP Cookies
 Directly manipulating the HTTP header using the PHP
header()function
 Use the PHP setcookie()function
 setcookie (name,value,expire, path,
domain, secure)
<?php
header(“Set-Cookie: mycookie=myvalue; path=/; domain=.example.com”);
# To make the cookie available on all subdomains of example.com, you'd
set it to '.example.com'.
?>
PHP
<?php
setcookie("MyCookie", $value, time()+3600*24);
setcookie("AnotherCookie", $value, time()+3600);
?>
PHP
The setcookie()Function
setcookie(name, value, expire, path, domain)
 Name and value correspond to $_COOKIE[$name] =
$value
 Expiration – cookie will no longer be read after the expiration
 Useful to use time in seconds relative to the present:
 time() + time in seconds until expiration
 Path and domain refer to where on the site the cookie is
valid
 Usually ‘/’ for path and the top-level domain
(yoursitename.com)
 To delete a cookie, set a new cookie with same
arguments but expiration in the past
Access PHP Cookies
 The $_COOKIE superglobal array makes a cookie a key-
value pairing
 Refer to $_COOKIE to retrieve a cookie
 Check with isset($_COOKIE[$cookie_name])
before trying to use the cookie’s value
 Cookies can only be set before any output is sent (e.g.
echo, print) and before <html><head>.
 Cookies only become visible on the next page load
Example: Set and Access Cookie
<?php
# createCookie.php Create and access a cookie
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html><body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";}
else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];}
?>
</body></html> PHP
86400 = 1 day
Before <html><body> and output
1st run 2nd run
Example: Cookie with Multiple Items
<?php
# multipleItemCookie.php
# set a cookie with 4 pieces of data
$strAddress = $_SERVER["REMOTE_ADDR"];
$strBrowser = $_SERVER["HTTP_USER_AGENT"];
$strServerName = $_SERVER["SERVER_NAME"];
$strInfo = "$strAddress::$strBrowser::$strServerName";
setcookie ("cookie4",$strInfo, time()+7200);
?>
<?php
# use explode() to retrieve the 4 pieces of data
$strReadCookie = $_COOKIE["cookie4"];
$arrListOfStrings = explode ("::", $strReadCookie);
echo "<p>$strInfo</p>";;
echo "<p>Your IP address is: $arrListOfStrings[1] </p>";
echo "<p>Client Browser is: $arrListOfStrings[2] </p>";
echo "<p>Server name is: $arrListOfStrings[3] </p>";
?>
PHP
Wrap-up Example: greeting.php
 First visit: form with a text field for user’s name
 Subsequent visits:Welcome message with the name
 Store the name field in a cookie:
 Key:“name”; value: the user’s name input into the form
 Remember: when a cookie is set (the setcookie() function call
is made), the cookie can only be accessed on the next request
1st run 5th run
Contents of HTTP Request and Response
Case 1: Cookies Already Set
# case 1: cookies already set
if(isset($_COOKIE["name"])) {
$cookie_exp = time()+60*60; // one hour
$name = $_COOKIE["name"];
setcookie("name", $name, $cookie_exp);
if (isset($_COOKIE["visits"])) { $num_visits =
$_COOKIE["visits"]+1;
setcookie("visits", $num_visits, $cookie_exp);
}
echo "Welcome $name! ";
if (isset($_COOKIE["visits"])) {
echo "You've visited $num_visits times"; }
} PHP
Case 2&3: First and Second Visits
# case 2: upon submission of form
else if (isset($_GET["name"])) {
$name = $_GET["name"];
setcookie("name", $name, $cookie_exp);
setcookie("visits", 2, $cookie_exp);
echo "Welcome $name! This is your second visit.";
}
# case 3: first visit: need to show form
else {
# HereDoc
# Complex data types in strings must be surrounded by {} for
them to be parsed as variables
$form = <<< FORM
<form action="{$_SERVER["PHP_SELF"]}" method="get">
Enter your name here: <input type="text" name="name" />
<br /><input type="submit" />
</form>
FORM;
echo $form; PHP
Sessions
Cookies vs. Sessions
 Two main disadvantages of cookies
 Limited in size by browser
 Stored client-side can be tampered with
 Sessions store user data on the server-side
 Limited only by server space
 Cannot be modified by users
 A potential downside to sessions is that they expire when
the browser is closed
A session is a semi-permanent interactive information
interchange, between two or more communicating devices
How Session Works?
 The first time a web client visits a server, the server sends a
unique "session ID" to the web client for the client to keep.
 Session ID is typically stored in the cookies.
 The session ID is used by the server to identify the client.
 For each session ID created, the server also creates a storage
space. Server-side scripts that receive the same session ID
share the same storage space.
 The storage space is typically implemented as a map-liked data structure.
 In PHP, it is an associative array named $_SESSION[].
 A session's "storage space" is only kept alive for a period of
time (session period) or until it is explicitly deleted.
Example
Crucially, sessions are easy to implement as PHP does all
the work!
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
 More secure, once established, no data is sent back and
forth between the machines
 Works even if cookies are disabled
PHP Session Start/Resume
 You must start up the session before using it
 Call session_start() at top of every page before
<html> tag
 This tells PHP that a session is requested.
<?php
session_start();
?>
<html>
<body>
</body>
</html> PHP
PHP Session Start/Resume (cont.)
 PHP looks for a valid session ID in the $_COOKIE or
$_GET superglobals
 If found
 Initializes the data
 If not found
 Create new session ID at the server end
 Session ID looks 26fe536a534d3c7cde4297abb45e275a to
make it unique
PHP Session Access
 Access data using the $_SESSION superglobal, just like
$_COOKIE, $_GET, or $_POST
<?php
#visitCountSession.php
session_start();
if (isset($_SESSION["count"])) {
$_SESSION["count"] += 1;
echo "You have visited here {$_SESSION["count"]} times";
}
else {
$_SESSION["count"] = 1;
echo "You have visited once";
}
?> PHP
PHP Session Propagation
 Sessions need to pass the session id between pages as a
user browses to track the session.
 It can do this in two ways:
 Cookie propagation
 URL propagation
 The default setup of a PHP server is to use both
methods.
 it checks whether the user has cookies enabled.
 If cookies are on, PHP uses cookie propagation. If cookies are
off it uses URL propagation.
Cookie Propagation
 A cookie is stored on the users PC containing the
session id.
 It is read in whenever session_start(); is
called to initialize the session.
 Default behaviour is a cookie that expires when the
browser is closed. Cookie properties can be modified
with session_set_cookie_params if
required.
URL Propagation
 The session id is propagated in the URL
 e.g.
…some_folder/index.php?sid=26fe536a534d3c7cde
4297abb45e275a
 PHP provides a global constant to append the session id
to any internal links, SID.
 e.g.
<a href="nextpage.php?<?=SID?>">Next page</a>
Session Expiry
 By default, PHP sessions expire:
 after a certain length of inactivity (default 1440s), the PHP
garbage collection processes deletes session variables.
 Important as most sessions will not be explicitly destroyed.
 if propagated by cookies, default is to set a cookie that is
destroyed when the browser is closed.
 If URL propagated, session id is lost as soon as navigate away
from the site.
unset() and session_destroy()
 Remove an individual element of the $_SESSION
superglobal
 unset($_SESSION[‘key_name’])
 The session still exists and can be modified
 Destroy the entire session, remove all data
 session_destroy()
 Destroys all data registered to a session
 Does not unset session global variables and cookies associated
with the session
 Need to call session_start() to start a new session
 Not normally done - leave to timeout
Example: Destroying a Session
 A more complete example at
 http://php.net/manual/en/function.session-destroy.php
<?php
#destroy session
session_start();
?>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html> PHP
Wrap-up Example: User Login
 loginForm.php
 Create a form to input user name and password
 login.php
 Validate user name and password
 content.php
 If logged in, show content page
 Logout.html
 Webpage for logout
 Logout.php
 Delete session
Recap: a Comparison
COOKIES SESSIONS
Where is data stored Locally on client Remotely on server
Expiration? Variable – determined
when cookie is set
Session is destroyed
when the browser is
closed
Size limit? Depends on browser Depends only on server
(practically no size limit)
Accessing information $_COOKIE $_SESSION
General use? Remember small things
about user, such as login
name. Remember things
after re-opening
browser
Remember varying
amount of data about
the user in one
browsing “session”
Ad

More Related Content

Similar to PHP-Cookies-Sessions.pdf (20)

Php session
Php sessionPhp session
Php session
argusacademy
 
season management in php (WT)
season management in php (WT)season management in php (WT)
season management in php (WT)
kunjan shah
 
Cookies & Session
Cookies & SessionCookies & Session
Cookies & Session
university of education,Lahore
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introduction
Programmer Blog
 
Web app development_cookies_sessions_14
Web app development_cookies_sessions_14Web app development_cookies_sessions_14
Web app development_cookies_sessions_14
Hassen Poreya
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
salissal
 
19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx
ssuser4a97d3
 
Cookies
CookiesCookies
Cookies
Preet Kanwal
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
baabtra.com - No. 1 supplier of quality freshers
 
lecture 12.pptx
lecture 12.pptxlecture 12.pptx
lecture 12.pptx
ITNet
 
PHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSPHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONS
Degu8
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
Nisa Soomro
 
Parameter Passing & Session Tracking in PHP
Parameter Passing & Session Tracking in PHPParameter Passing & Session Tracking in PHP
Parameter Passing & Session Tracking in PHP
amichoksi
 
javaScriptCookies.pptx
javaScriptCookies.pptxjavaScriptCookies.pptx
javaScriptCookies.pptx
MattMarino13
 
Session,cookies
Session,cookiesSession,cookies
Session,cookies
rkmourya511
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
UdaAs PaNchi
 
Ecom2
Ecom2Ecom2
Ecom2
Santosh Pandey
 
4 php-advanced
4 php-advanced4 php-advanced
4 php-advanced
Achchuthan Yogarajah
 
Sessions in php
Sessions in php Sessions in php
Sessions in php
Mudasir Syed
 
Session Management & Cookies In Php
Session Management & Cookies In PhpSession Management & Cookies In Php
Session Management & Cookies In Php
Harit Kothari
 
season management in php (WT)
season management in php (WT)season management in php (WT)
season management in php (WT)
kunjan shah
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introduction
Programmer Blog
 
Web app development_cookies_sessions_14
Web app development_cookies_sessions_14Web app development_cookies_sessions_14
Web app development_cookies_sessions_14
Hassen Poreya
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
salissal
 
19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx
ssuser4a97d3
 
lecture 12.pptx
lecture 12.pptxlecture 12.pptx
lecture 12.pptx
ITNet
 
PHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSPHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONS
Degu8
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
Nisa Soomro
 
Parameter Passing & Session Tracking in PHP
Parameter Passing & Session Tracking in PHPParameter Passing & Session Tracking in PHP
Parameter Passing & Session Tracking in PHP
amichoksi
 
javaScriptCookies.pptx
javaScriptCookies.pptxjavaScriptCookies.pptx
javaScriptCookies.pptx
MattMarino13
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
UdaAs PaNchi
 
Session Management & Cookies In Php
Session Management & Cookies In PhpSession Management & Cookies In Php
Session Management & Cookies In Php
Harit Kothari
 

Recently uploaded (20)

new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
Ad

PHP-Cookies-Sessions.pdf

  • 1. PHP Cookies and Sessions COMP 2021 Unix and Script Programming
  • 2. HTTP - a ‘Stateless’ Environment stateless (adj.) Having no information about what occurred previously.  HTTP is stateless – it does not keep track of the client between requests  When you browse the web, you are not always connected to the server  Once the request has been processed and returned from the server, the connection is closed  Connection needs to be re-opened when you need new information or refresh
  • 3. Cookies and Sessions  But sometimes we need to keep track of information, or have persistent data  Shopping cart  “Remember me” on login sites  PHP sessions and cookies are mechanisms for introducing state into HTTP transactions.  Cookies – small file stored client-side  Sessions – relevant data stored on the server HTTP server Client Cookie Session
  • 4. Is PHP Stateless?  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']  It is possible to add data to a database/text file to add persistent data, although this is not connected with a particular user…
  • 6. What is a Cookie?  HTTP cookies are data which a server-side script sends to a web client to keep for a period of time.  a small text file that is stored on a user’s computer  On every subsequent HTTP request, the web client automatically sends the cookies back to server (unless the cookie support is turned off).  The cookies are embedded in the HTTP header (and therefore not visible to the users).
  • 7. How do HTTP Cookies work? Cookies are transferred between server and client according to HTTP 1. User sends a HTTP request for page for the first time. 2. Server sends back the HTTP response (e.g. HTML webpage) to the browser AND stores some data in a cookie on the user’s PC. 3. At the next page request, all cookie data associated with this domain is sent too.
  • 8. Cookie Fact  Cookies are sent from the server to the client via “Set- Cookie” headers  Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure  Each cookie on the user’s computer is connected to a particular domain.  Each cookie be used to store up to 4kB of data.  A maximum number of cookies can be stored on a user’s PC per domain is browser dependent  Usually a few tens  Cookies can be created with JavaScript or PHP elearning.strathmore.edu apps.strathmore.edu attachment.strathmore.edu .strathmore.edu
  • 9. The USER is in Control  Cookies are stored client-side  Cookie is stored (or persistent) only if there is an expiry date  Otherwise it is deleted when leaving browser  They can be turned on and off at will by the user  Never trust them completely: they can be easily viewed, modified or created by a 3rd party  Exact location depends on browser, e.g. IE cookies
  • 10. Example: Default IE Cookie Setting
  • 11. Create PHP Cookies  Directly manipulating the HTTP header using the PHP header()function  Use the PHP setcookie()function  setcookie (name,value,expire, path, domain, secure) <?php header(“Set-Cookie: mycookie=myvalue; path=/; domain=.example.com”); # To make the cookie available on all subdomains of example.com, you'd set it to '.example.com'. ?> PHP <?php setcookie("MyCookie", $value, time()+3600*24); setcookie("AnotherCookie", $value, time()+3600); ?> PHP
  • 12. The setcookie()Function setcookie(name, value, expire, path, domain)  Name and value correspond to $_COOKIE[$name] = $value  Expiration – cookie will no longer be read after the expiration  Useful to use time in seconds relative to the present:  time() + time in seconds until expiration  Path and domain refer to where on the site the cookie is valid  Usually ‘/’ for path and the top-level domain (yoursitename.com)  To delete a cookie, set a new cookie with same arguments but expiration in the past
  • 13. Access PHP Cookies  The $_COOKIE superglobal array makes a cookie a key- value pairing  Refer to $_COOKIE to retrieve a cookie  Check with isset($_COOKIE[$cookie_name]) before trying to use the cookie’s value  Cookies can only be set before any output is sent (e.g. echo, print) and before <html><head>.  Cookies only become visible on the next page load
  • 14. Example: Set and Access Cookie <?php # createCookie.php Create and access a cookie $cookie_name = "user"; $cookie_value = "John Doe"; setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); ?> <html><body> <?php if(!isset($_COOKIE[$cookie_name])) { echo "Cookie named '" . $cookie_name . "' is not set!";} else { echo "Cookie '" . $cookie_name . "' is set!<br>"; echo "Value is: " . $_COOKIE[$cookie_name];} ?> </body></html> PHP 86400 = 1 day Before <html><body> and output 1st run 2nd run
  • 15. Example: Cookie with Multiple Items <?php # multipleItemCookie.php # set a cookie with 4 pieces of data $strAddress = $_SERVER["REMOTE_ADDR"]; $strBrowser = $_SERVER["HTTP_USER_AGENT"]; $strServerName = $_SERVER["SERVER_NAME"]; $strInfo = "$strAddress::$strBrowser::$strServerName"; setcookie ("cookie4",$strInfo, time()+7200); ?> <?php # use explode() to retrieve the 4 pieces of data $strReadCookie = $_COOKIE["cookie4"]; $arrListOfStrings = explode ("::", $strReadCookie); echo "<p>$strInfo</p>";; echo "<p>Your IP address is: $arrListOfStrings[1] </p>"; echo "<p>Client Browser is: $arrListOfStrings[2] </p>"; echo "<p>Server name is: $arrListOfStrings[3] </p>"; ?> PHP
  • 16. Wrap-up Example: greeting.php  First visit: form with a text field for user’s name  Subsequent visits:Welcome message with the name  Store the name field in a cookie:  Key:“name”; value: the user’s name input into the form  Remember: when a cookie is set (the setcookie() function call is made), the cookie can only be accessed on the next request 1st run 5th run
  • 17. Contents of HTTP Request and Response
  • 18. Case 1: Cookies Already Set # case 1: cookies already set if(isset($_COOKIE["name"])) { $cookie_exp = time()+60*60; // one hour $name = $_COOKIE["name"]; setcookie("name", $name, $cookie_exp); if (isset($_COOKIE["visits"])) { $num_visits = $_COOKIE["visits"]+1; setcookie("visits", $num_visits, $cookie_exp); } echo "Welcome $name! "; if (isset($_COOKIE["visits"])) { echo "You've visited $num_visits times"; } } PHP
  • 19. Case 2&3: First and Second Visits # case 2: upon submission of form else if (isset($_GET["name"])) { $name = $_GET["name"]; setcookie("name", $name, $cookie_exp); setcookie("visits", 2, $cookie_exp); echo "Welcome $name! This is your second visit."; } # case 3: first visit: need to show form else { # HereDoc # Complex data types in strings must be surrounded by {} for them to be parsed as variables $form = <<< FORM <form action="{$_SERVER["PHP_SELF"]}" method="get"> Enter your name here: <input type="text" name="name" /> <br /><input type="submit" /> </form> FORM; echo $form; PHP
  • 21. Cookies vs. Sessions  Two main disadvantages of cookies  Limited in size by browser  Stored client-side can be tampered with  Sessions store user data on the server-side  Limited only by server space  Cannot be modified by users  A potential downside to sessions is that they expire when the browser is closed A session is a semi-permanent interactive information interchange, between two or more communicating devices
  • 22. How Session Works?  The first time a web client visits a server, the server sends a unique "session ID" to the web client for the client to keep.  Session ID is typically stored in the cookies.  The session ID is used by the server to identify the client.  For each session ID created, the server also creates a storage space. Server-side scripts that receive the same session ID share the same storage space.  The storage space is typically implemented as a map-liked data structure.  In PHP, it is an associative array named $_SESSION[].  A session's "storage space" is only kept alive for a period of time (session period) or until it is explicitly deleted.
  • 23. Example Crucially, sessions are easy to implement as PHP does all the work!
  • 24. 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  More secure, once established, no data is sent back and forth between the machines  Works even if cookies are disabled
  • 25. PHP Session Start/Resume  You must start up the session before using it  Call session_start() at top of every page before <html> tag  This tells PHP that a session is requested. <?php session_start(); ?> <html> <body> </body> </html> PHP
  • 26. PHP Session Start/Resume (cont.)  PHP looks for a valid session ID in the $_COOKIE or $_GET superglobals  If found  Initializes the data  If not found  Create new session ID at the server end  Session ID looks 26fe536a534d3c7cde4297abb45e275a to make it unique
  • 27. PHP Session Access  Access data using the $_SESSION superglobal, just like $_COOKIE, $_GET, or $_POST <?php #visitCountSession.php session_start(); if (isset($_SESSION["count"])) { $_SESSION["count"] += 1; echo "You have visited here {$_SESSION["count"]} times"; } else { $_SESSION["count"] = 1; echo "You have visited once"; } ?> PHP
  • 28. PHP Session Propagation  Sessions need to pass the session id between pages as a user browses to track the session.  It can do this in two ways:  Cookie propagation  URL propagation  The default setup of a PHP server is to use both methods.  it checks whether the user has cookies enabled.  If cookies are on, PHP uses cookie propagation. If cookies are off it uses URL propagation.
  • 29. Cookie Propagation  A cookie is stored on the users PC containing the session id.  It is read in whenever session_start(); is called to initialize the session.  Default behaviour is a cookie that expires when the browser is closed. Cookie properties can be modified with session_set_cookie_params if required.
  • 30. URL Propagation  The session id is propagated in the URL  e.g. …some_folder/index.php?sid=26fe536a534d3c7cde 4297abb45e275a  PHP provides a global constant to append the session id to any internal links, SID.  e.g. <a href="nextpage.php?<?=SID?>">Next page</a>
  • 31. Session Expiry  By default, PHP sessions expire:  after a certain length of inactivity (default 1440s), the PHP garbage collection processes deletes session variables.  Important as most sessions will not be explicitly destroyed.  if propagated by cookies, default is to set a cookie that is destroyed when the browser is closed.  If URL propagated, session id is lost as soon as navigate away from the site.
  • 32. unset() and session_destroy()  Remove an individual element of the $_SESSION superglobal  unset($_SESSION[‘key_name’])  The session still exists and can be modified  Destroy the entire session, remove all data  session_destroy()  Destroys all data registered to a session  Does not unset session global variables and cookies associated with the session  Need to call session_start() to start a new session  Not normally done - leave to timeout
  • 33. Example: Destroying a Session  A more complete example at  http://php.net/manual/en/function.session-destroy.php <?php #destroy session session_start(); ?> <html> <body> <?php // remove all session variables session_unset(); // destroy the session session_destroy(); ?> </body> </html> PHP
  • 34. Wrap-up Example: User Login  loginForm.php  Create a form to input user name and password  login.php  Validate user name and password  content.php  If logged in, show content page  Logout.html  Webpage for logout  Logout.php  Delete session
  • 35. Recap: a Comparison COOKIES SESSIONS Where is data stored Locally on client Remotely on server Expiration? Variable – determined when cookie is set Session is destroyed when the browser is closed Size limit? Depends on browser Depends only on server (practically no size limit) Accessing information $_COOKIE $_SESSION General use? Remember small things about user, such as login name. Remember things after re-opening browser Remember varying amount of data about the user in one browsing “session”