SlideShare una empresa de Scribd logo
1 de 21
Descargar para leer sin conexión
PHP Cookies & Session
Cookies
 HTTP cookies are data which a server-side script
sends to a web client to keep for a period of time.
 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).
Cookies
 Shortcomings of using cookies to keep data
 User may turn off cookies support.
 Data are kept with the browser
 Users using the same browser share the cookies.
 Limited number of cookies (20) per server/domain and
limited size (4k bytes) per cookie
 Client can temper with cookies
 Modify cookie files, use JavaScript to create/modify cookies, etc.
 Notes
 Don't always rely on cookies as the client may have
turned off cookies support.
 Don't store sensitive info in cookies
PHP – Accessing Cookies
 To set a cookie, call setcookie()
 e.g., setcookie('username', 'Joe');
 To delete a cookie (use setcookie() without a value)
 e.g., setcookie('username');
 To retrieve a cookie, refer to $COOKIE
 e.g. $username = $_COOKIE('username');
 Note:
 Cookies can only be set before any output is sent.
 You cannot set and access a cookie in the same page. Cookies set
in a page are available only in the future requests.
PHP – More About Setting Cookies …
setcookie(name, value, expiration, path,
domain, secure, httponly)
 expiration
 Cookie expiration time in seconds
 0  The cookie is not to be stored persistently and will be deleted
when the web client closes.
 Negative value  Request the web client to delete the cookie
 e.g.:
setcookie('username', 'Joe', time() + 1800); // Expire in 30 minutes
PHP – More About Setting Cookies …
 path
 Sets the path to which the cookie applies.
 The cookie is only visible to all the pages in that directory and its
sub-directories.
 If set to '/', the cookie will be available within the entire domain.
 If set to '/foo/', the cookie will only be available within the /foo/
directory and all sub-directories such as /foo/bar/ of domain .
 The default value is the current directory that the cookie is being set
in.
PHP – More About Setting Cookies …
 domain
 The domain that the cookie is available.
 To make the cookie available on all subdomains of example.com,
you'd set it to '.example.com'.
 Setting it to 'www.example.com' will make the cookie only
available in the www subdomain.
 secure
 Indicates that the cookie should only be transmitted over a secure
HTTPS connection from the client. When set to TRUE, the cookie
will only be set if a secure connection exists. The default is FALSE.
 httponly
 When TRUE the cookie will be made accessible only through the
HTTP protocol.
URL-Rewriting
 Append the data to the URL
 e.g.: http://www.xyz.com/foo.php?name1=value1&name2=value2
 Data are kept along with the "page"
 Need to append the data to every URL in the page that needs to
carry the data to another page.
 Every 'name' and 'value' should be URL encoded using
urlencode().
 Shortcoming of using URL-rewriting to keep data:
 Limited number of characters in an URL
 Not suitable for sensitive info
 You can encrypt the data to improve security (e.g., www.ebay.com)
 Breaks when a user access a static HTML page
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
PHP – URL-Rewriting Example
<?php
// Append all (key, value) pairs in $array to $url as
// $url?key1=value1&key2=value2&…
function append_data_to_url($url, $array) {
$first = true;
$url .= '?';
foreach ($array as $key => $value) {
if (! $first)
$url .= '&';
else
$first = false;
$url .= urlencode($key) . '=' . urlencode($value);
}
return $url;
}
// Continue next page
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
PHP – URL-Rewriting Example
// A script that lists 20 items per page
$current_page = $_REQUEST['page'];
$sort_order = $_REQUEST['sort'];
// Perform validation and set default values here …
// Create parameters that need to be appended to URL
$params = array('page' => $current_page + 1,
'sort' => $sort_order);
// Append the above parameters to the URL that links
// to the next page
$next_page_url = append_data_to_url(
$_SERVER['PHP_SELF'], $params);
// Repeat for other URLs that need to carry data
// in the URL …
?>
36
37
38
39
40
41
42
43
44
45
46
PHP – URL-Rewriting Example
 In this example, when the user clicks the "Next Page" link,
the script will knows which page to display and what sorting
order to use.
<html><head><title>URL-Rewriting Example</title></head>
<body>
<?php
// Retrieve and display current page's data here …
?>
<a href="<?php echo $next_page_url;?>">Next Page</a>
…
</body></html>
Hidden Fields in HTML Form
 Data are encoded as hidden fields in HTML form as:
<input type="hidden" name="username" value="CJ Yuan" />
 Shortcoming of using URL-rewriting to keep data:
 Require HTML form elements
Session
 A session is a period of time in which all activities
happened within the period by the same web
client are considered "related" (typically belong to
the same application.)
 Session Tracking – keeping track of users as they
traverse from one web page (generated from a
script) to another within a website (or within a web
application).
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.
1
2
3
4
5
6
7
8
9
10
PHP – Participating in a session
The first time session_start() is called, it will attempt to send a cookie
named PHPSESSID with a generated session ID made up of 32
hexadecimal letters. The data stored in $_SESSION[] will be saved in an
external file when the script exits.
<?php
// Must call this function first in all scripts that
// need to participate in the same session.
session_start();
// Now we can read/write data from/to $_SESSION[]
if (authenticate($_POST['user'], $_POST['passwd'])) {
// Use this value to remember if a user has 'logged in'
$_SESSION['user'] = $_POST['user'];
}
else
unset($_SESSION['user']);
…
?>
login.php
1
2
3
4
5
6
7
8
9
10
PHP – Participating in a session (continue)
If a user has successfully logged in through login.php, then
The next time session_start() is called, it will load the session data from
a file into $_SESSION[] based on the value of PHPSESSID.
<?php
// To participate in the session
session_start();
// Session data set in login.php are available here
if (! isset($_SESSION['user'])) {
// User has not yet logged on
}
…
?>
another_file.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
PHP – Ending a session
Note: session_name() returns the name of the cookie that stores the
session ID.
<?php
// To start or participate in a session.
session_start();
$_SESSION = array(); // Clearing all session data
// Delete the cookie that stores the session ID to KILL the session
if (isset($_COOKIE[session_name()]))
setcookie(session_name(), '', time()-3600, '/');
// Finally, destroy the session (Deleting
// the session data stored in the file)
session_destroy();
?>
logout.php
PHP – Setting Session Parameters in php.ini
Some of the session related parameters in "php.ini":
; This option enables administrators to make their users invulnerable to
; attacks which involve passing session ids in URLs; defaults to 0.
; session.use_only_cookies = 1
; Name of the session (used as cookie name).
session.name = PHPSESSID
; Initialize session on request startup.
session.auto_start = 0
; Lifetime in seconds of cookie or, if 0, until browser is restarted.
session.cookie_lifetime = 0
; The path for which the cookie is valid.
session.cookie_path = /
; The domain for which the cookie is valid.
session.cookie_domain =
PHP – Function For Setting Session Parameters
void session_set_cookie_params(
int $lifetime, string $path, string $domain,
bool $secure=false, bool $httponly=false )
 Set cookie parameters defined in the php.ini file. The effect
of this function only lasts for the duration of the script. Thus,
you need to call this function for every request and before
session_start() is called.
 Default value of $path is '/'. To prevent session ID from
being discovered by other PHP scripts running in the same
domain, you should set $path to the subfolder where your
scripts are stored.
Combined Use
 All of Cookies, URL-rewriting, Hidden Fields, and
Session can be simultaneously used in a web
application.
 Cookies: Can persist data for long period but is not
suitable for keeping sensitive data or large amount of
data.
 URL-rewriting: Keep data along with page
 Hidden Fields: Keep data along with page (can keep
more data but requires HTML form)
 Session Objects: Keep "short-live" data shared among
the server-side scripts within a web application for a
particular web client.
Summary
 Session Management
 Cookies
 URL-Rewriting
 Hidden Fields in HTML Form
 High level APIs in Java and HttpSession Objects.
 References
 http://en.wikipedia.org/wiki/HTTP_cookie
 PHP Manual – Session Handling
 http://hk.php.net/manual/en/book.session.php

Más contenido relacionado

La actualidad más candente

season management in php (WT)
season management in php (WT)season management in php (WT)
season management in php (WT)kunjan shah
 
Parameter Passing & Session Tracking in PHP
Parameter Passing & Session Tracking in PHPParameter Passing & Session Tracking in PHP
Parameter Passing & Session Tracking in PHPamichoksi
 
Creating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login SystemCreating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login SystemAzharul Haque Shohan
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessionsUdaAs PaNchi
 
New: Two Methods of Installing Drupal on Windows XP with XAMPP
New: Two Methods of Installing Drupal on Windows XP with XAMPPNew: Two Methods of Installing Drupal on Windows XP with XAMPP
New: Two Methods of Installing Drupal on Windows XP with XAMPPRupesh Kumar
 
Php Server Var
Php Server VarPhp Server Var
Php Server Vararvind34
 
httpd — Apache Web Server
httpd — Apache Web Serverhttpd — Apache Web Server
httpd — Apache Web Serverwebhostingguy
 
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...webhostingguy
 
Php basic for vit university
Php basic for vit universityPhp basic for vit university
Php basic for vit universityMandakini Kumari
 

La actualidad más candente (20)

season management in php (WT)
season management in php (WT)season management in php (WT)
season management in php (WT)
 
Parameter Passing & Session Tracking in PHP
Parameter Passing & Session Tracking in PHPParameter Passing & Session Tracking in PHP
Parameter Passing & Session Tracking in PHP
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
Session handling in php
Session handling in phpSession handling in php
Session handling in php
 
Manish
ManishManish
Manish
 
Creating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login SystemCreating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login System
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
New: Two Methods of Installing Drupal on Windows XP with XAMPP
New: Two Methods of Installing Drupal on Windows XP with XAMPPNew: Two Methods of Installing Drupal on Windows XP with XAMPP
New: Two Methods of Installing Drupal on Windows XP with XAMPP
 
Php Server Var
Php Server VarPhp Server Var
Php Server Var
 
httpd — Apache Web Server
httpd — Apache Web Serverhttpd — Apache Web Server
httpd — Apache Web Server
 
Php
PhpPhp
Php
 
PHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and SessionsPHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and Sessions
 
backend
backendbackend
backend
 
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
 
Php sessions
Php sessionsPhp sessions
Php sessions
 
Sessions n cookies
Sessions n cookiesSessions n cookies
Sessions n cookies
 
Introduction to php web programming - get and post
Introduction to php  web programming - get and postIntroduction to php  web programming - get and post
Introduction to php web programming - get and post
 
Php basics
Php basicsPhp basics
Php basics
 
extending-php
extending-phpextending-php
extending-php
 
Php basic for vit university
Php basic for vit universityPhp basic for vit university
Php basic for vit university
 

Similar a 4.4 PHP Session

PHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdfPHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdfHumphreyOwuor1
 
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.pptLecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.pptSreejithVP7
 
Lecture8 php page control by okello erick
Lecture8 php page control by okello erickLecture8 php page control by okello erick
Lecture8 php page control by okello erickokelloerick
 
PHP SESSIONS & COOKIE.pptx
PHP SESSIONS & COOKIE.pptxPHP SESSIONS & COOKIE.pptx
PHP SESSIONS & COOKIE.pptxShitalGhotekar
 
Web app development_cookies_sessions_14
Web app development_cookies_sessions_14Web app development_cookies_sessions_14
Web app development_cookies_sessions_14Hassen Poreya
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessionssalissal
 
Session Management & Cookies In Php
Session Management & Cookies In PhpSession Management & Cookies In Php
Session Management & Cookies In PhpHarit Kothari
 
LAMP security practices
LAMP security practicesLAMP security practices
LAMP security practicesAmit Kejriwal
 
Web application security
Web application securityWeb application security
Web application securityRavi Raj
 
javaScriptCookies.pptx
javaScriptCookies.pptxjavaScriptCookies.pptx
javaScriptCookies.pptxMattMarino13
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introductionProgrammer Blog
 
murach12.pptx
murach12.pptxmurach12.pptx
murach12.pptxxiso
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and SessionsNisa Soomro
 

Similar a 4.4 PHP Session (20)

PHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdfPHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdf
 
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.pptLecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
 
Lecture8 php page control by okello erick
Lecture8 php page control by okello erickLecture8 php page control by okello erick
Lecture8 php page control by okello erick
 
Sessions and cookies
Sessions and cookiesSessions and cookies
Sessions and cookies
 
PHP SESSIONS & COOKIE.pptx
PHP SESSIONS & COOKIE.pptxPHP SESSIONS & COOKIE.pptx
PHP SESSIONS & COOKIE.pptx
 
Php session
Php sessionPhp session
Php session
 
Web app development_cookies_sessions_14
Web app development_cookies_sessions_14Web app development_cookies_sessions_14
Web app development_cookies_sessions_14
 
Session,cookies
Session,cookiesSession,cookies
Session,cookies
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
Session Management & Cookies In Php
Session Management & Cookies In PhpSession Management & Cookies In Php
Session Management & Cookies In Php
 
LAMP security practices
LAMP security practicesLAMP security practices
LAMP security practices
 
Web application security
Web application securityWeb application security
Web application security
 
javaScriptCookies.pptx
javaScriptCookies.pptxjavaScriptCookies.pptx
javaScriptCookies.pptx
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introduction
 
Cookies & Session
Cookies & SessionCookies & Session
Cookies & Session
 
murach12.pptx
murach12.pptxmurach12.pptx
murach12.pptx
 
PHP 2
PHP 2PHP 2
PHP 2
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
 
Php BASIC
Php BASICPhp BASIC
Php BASIC
 

Más de Jalpesh Vasa

Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Jalpesh Vasa
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Jalpesh Vasa
 
3.2.1 javascript regex example
3.2.1 javascript regex example3.2.1 javascript regex example
3.2.1 javascript regex exampleJalpesh Vasa
 
3.2 javascript regex
3.2 javascript regex3.2 javascript regex
3.2 javascript regexJalpesh Vasa
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOMJalpesh Vasa
 
2 introduction css
2 introduction css2 introduction css
2 introduction cssJalpesh Vasa
 
1 web technologies
1 web technologies1 web technologies
1 web technologiesJalpesh Vasa
 
Remote Method Invocation in JAVA
Remote Method Invocation in JAVARemote Method Invocation in JAVA
Remote Method Invocation in JAVAJalpesh Vasa
 
Kotlin for android development
Kotlin for android developmentKotlin for android development
Kotlin for android developmentJalpesh Vasa
 

Más de Jalpesh Vasa (15)

Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
 
5. HTML5
5. HTML55. HTML5
5. HTML5
 
4.3 MySQL + PHP
4.3 MySQL + PHP4.3 MySQL + PHP
4.3 MySQL + PHP
 
4.2 PHP Function
4.2 PHP Function4.2 PHP Function
4.2 PHP Function
 
4.1 PHP Arrays
4.1 PHP Arrays4.1 PHP Arrays
4.1 PHP Arrays
 
4 Basic PHP
4 Basic PHP4 Basic PHP
4 Basic PHP
 
3.2.1 javascript regex example
3.2.1 javascript regex example3.2.1 javascript regex example
3.2.1 javascript regex example
 
3.2 javascript regex
3.2 javascript regex3.2 javascript regex
3.2 javascript regex
 
3. Java Script
3. Java Script3. Java Script
3. Java Script
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOM
 
2 introduction css
2 introduction css2 introduction css
2 introduction css
 
1 web technologies
1 web technologies1 web technologies
1 web technologies
 
Remote Method Invocation in JAVA
Remote Method Invocation in JAVARemote Method Invocation in JAVA
Remote Method Invocation in JAVA
 
Kotlin for android development
Kotlin for android developmentKotlin for android development
Kotlin for android development
 

Último

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxdhanalakshmis0310
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 

Último (20)

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 

4.4 PHP Session

  • 1. PHP Cookies & Session
  • 2. Cookies  HTTP cookies are data which a server-side script sends to a web client to keep for a period of time.  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).
  • 3. Cookies  Shortcomings of using cookies to keep data  User may turn off cookies support.  Data are kept with the browser  Users using the same browser share the cookies.  Limited number of cookies (20) per server/domain and limited size (4k bytes) per cookie  Client can temper with cookies  Modify cookie files, use JavaScript to create/modify cookies, etc.  Notes  Don't always rely on cookies as the client may have turned off cookies support.  Don't store sensitive info in cookies
  • 4. PHP – Accessing Cookies  To set a cookie, call setcookie()  e.g., setcookie('username', 'Joe');  To delete a cookie (use setcookie() without a value)  e.g., setcookie('username');  To retrieve a cookie, refer to $COOKIE  e.g. $username = $_COOKIE('username');  Note:  Cookies can only be set before any output is sent.  You cannot set and access a cookie in the same page. Cookies set in a page are available only in the future requests.
  • 5. PHP – More About Setting Cookies … setcookie(name, value, expiration, path, domain, secure, httponly)  expiration  Cookie expiration time in seconds  0  The cookie is not to be stored persistently and will be deleted when the web client closes.  Negative value  Request the web client to delete the cookie  e.g.: setcookie('username', 'Joe', time() + 1800); // Expire in 30 minutes
  • 6. PHP – More About Setting Cookies …  path  Sets the path to which the cookie applies.  The cookie is only visible to all the pages in that directory and its sub-directories.  If set to '/', the cookie will be available within the entire domain.  If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain .  The default value is the current directory that the cookie is being set in.
  • 7. PHP – More About Setting Cookies …  domain  The domain that the cookie is available.  To make the cookie available on all subdomains of example.com, you'd set it to '.example.com'.  Setting it to 'www.example.com' will make the cookie only available in the www subdomain.  secure  Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client. When set to TRUE, the cookie will only be set if a secure connection exists. The default is FALSE.  httponly  When TRUE the cookie will be made accessible only through the HTTP protocol.
  • 8. URL-Rewriting  Append the data to the URL  e.g.: http://www.xyz.com/foo.php?name1=value1&name2=value2  Data are kept along with the "page"  Need to append the data to every URL in the page that needs to carry the data to another page.  Every 'name' and 'value' should be URL encoded using urlencode().  Shortcoming of using URL-rewriting to keep data:  Limited number of characters in an URL  Not suitable for sensitive info  You can encrypt the data to improve security (e.g., www.ebay.com)  Breaks when a user access a static HTML page
  • 9. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 PHP – URL-Rewriting Example <?php // Append all (key, value) pairs in $array to $url as // $url?key1=value1&key2=value2&… function append_data_to_url($url, $array) { $first = true; $url .= '?'; foreach ($array as $key => $value) { if (! $first) $url .= '&'; else $first = false; $url .= urlencode($key) . '=' . urlencode($value); } return $url; } // Continue next page
  • 10. 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 PHP – URL-Rewriting Example // A script that lists 20 items per page $current_page = $_REQUEST['page']; $sort_order = $_REQUEST['sort']; // Perform validation and set default values here … // Create parameters that need to be appended to URL $params = array('page' => $current_page + 1, 'sort' => $sort_order); // Append the above parameters to the URL that links // to the next page $next_page_url = append_data_to_url( $_SERVER['PHP_SELF'], $params); // Repeat for other URLs that need to carry data // in the URL … ?>
  • 11. 36 37 38 39 40 41 42 43 44 45 46 PHP – URL-Rewriting Example  In this example, when the user clicks the "Next Page" link, the script will knows which page to display and what sorting order to use. <html><head><title>URL-Rewriting Example</title></head> <body> <?php // Retrieve and display current page's data here … ?> <a href="<?php echo $next_page_url;?>">Next Page</a> … </body></html>
  • 12. Hidden Fields in HTML Form  Data are encoded as hidden fields in HTML form as: <input type="hidden" name="username" value="CJ Yuan" />  Shortcoming of using URL-rewriting to keep data:  Require HTML form elements
  • 13. Session  A session is a period of time in which all activities happened within the period by the same web client are considered "related" (typically belong to the same application.)  Session Tracking – keeping track of users as they traverse from one web page (generated from a script) to another within a website (or within a web application).
  • 14. 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.
  • 15. 1 2 3 4 5 6 7 8 9 10 PHP – Participating in a session The first time session_start() is called, it will attempt to send a cookie named PHPSESSID with a generated session ID made up of 32 hexadecimal letters. The data stored in $_SESSION[] will be saved in an external file when the script exits. <?php // Must call this function first in all scripts that // need to participate in the same session. session_start(); // Now we can read/write data from/to $_SESSION[] if (authenticate($_POST['user'], $_POST['passwd'])) { // Use this value to remember if a user has 'logged in' $_SESSION['user'] = $_POST['user']; } else unset($_SESSION['user']); … ?> login.php
  • 16. 1 2 3 4 5 6 7 8 9 10 PHP – Participating in a session (continue) If a user has successfully logged in through login.php, then The next time session_start() is called, it will load the session data from a file into $_SESSION[] based on the value of PHPSESSID. <?php // To participate in the session session_start(); // Session data set in login.php are available here if (! isset($_SESSION['user'])) { // User has not yet logged on } … ?> another_file.php
  • 17. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 PHP – Ending a session Note: session_name() returns the name of the cookie that stores the session ID. <?php // To start or participate in a session. session_start(); $_SESSION = array(); // Clearing all session data // Delete the cookie that stores the session ID to KILL the session if (isset($_COOKIE[session_name()])) setcookie(session_name(), '', time()-3600, '/'); // Finally, destroy the session (Deleting // the session data stored in the file) session_destroy(); ?> logout.php
  • 18. PHP – Setting Session Parameters in php.ini Some of the session related parameters in "php.ini": ; This option enables administrators to make their users invulnerable to ; attacks which involve passing session ids in URLs; defaults to 0. ; session.use_only_cookies = 1 ; Name of the session (used as cookie name). session.name = PHPSESSID ; Initialize session on request startup. session.auto_start = 0 ; Lifetime in seconds of cookie or, if 0, until browser is restarted. session.cookie_lifetime = 0 ; The path for which the cookie is valid. session.cookie_path = / ; The domain for which the cookie is valid. session.cookie_domain =
  • 19. PHP – Function For Setting Session Parameters void session_set_cookie_params( int $lifetime, string $path, string $domain, bool $secure=false, bool $httponly=false )  Set cookie parameters defined in the php.ini file. The effect of this function only lasts for the duration of the script. Thus, you need to call this function for every request and before session_start() is called.  Default value of $path is '/'. To prevent session ID from being discovered by other PHP scripts running in the same domain, you should set $path to the subfolder where your scripts are stored.
  • 20. Combined Use  All of Cookies, URL-rewriting, Hidden Fields, and Session can be simultaneously used in a web application.  Cookies: Can persist data for long period but is not suitable for keeping sensitive data or large amount of data.  URL-rewriting: Keep data along with page  Hidden Fields: Keep data along with page (can keep more data but requires HTML form)  Session Objects: Keep "short-live" data shared among the server-side scripts within a web application for a particular web client.
  • 21. Summary  Session Management  Cookies  URL-Rewriting  Hidden Fields in HTML Form  High level APIs in Java and HttpSession Objects.  References  http://en.wikipedia.org/wiki/HTTP_cookie  PHP Manual – Session Handling  http://hk.php.net/manual/en/book.session.php