SlideShare a Scribd company logo
1 of 22
Chapter 5
Cookies and Session
Contents
• Cookies and Sessions
• Describe the stateless model
• Explain the concepts of maintaining state with
sessions
• Create and Read data from sessions
What is a Cookie?
• A cookie is often used to identify a user.
• A cookie is a small file that the server embeds on
the user's computer.
• Each time the same computer requests a page
with a browser, it will send the cookie too.
• With PHP, you can both create and retrieve
cookie values.
• Cookies are primarily used to store the user’s
browsing history.
Create Cookies With PHP
• A cookie is created with the setcookie() function.
• Syntax:
setcookie(name, value, expire, path, domain, security);
• Parameters: The setcookie() function requires six
arguments in general which are:
Parameters:
• Name: It is used to set the name of the cookie.
• Value: It is used to set the value of the cookie.
• Expire: It is used to set the expiry timestamp of the cookie after which the
cookie can’t be accessed.
• Path: It is used to specify the path on the server for which the cookie will be
available.
• Domain: It is used to specify the domain for which the cookie is available.
• Security: It is used to indicate that the cookie should be sent only if a secure
HTTPS connection exists.
Cont.
• The following example creates a cookie named "user" with the
value "John Doe".
• The cookie will expire after 30 days (86400 * 30).
• The "/" means that the cookie is available in entire website
(otherwise, select the directory you prefer).
• We then retrieve the value of the cookie "user" (using the
global variable $_COOKIE).
• We also use the isset() function to find out if the cookie is set:
Operations that can be performed on
Cookies in PHP:
Creating Cookies:
• Creating a cookie named Auction_Item and
assigning the value Luxury Car to it.
• The cookie will expire after 2 days(2 days * 24
hours * 60 mins * 60 seconds).
Example
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 30 day
?>
<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>
Checking Whether a Cookie Is Set Or Not
• It is always advisable to check whether a cookie is
set or not before accessing its value.
• Therefore to check whether a cookie is set or not,
the PHP isset() function is used.
• To check whether a cookie “Auction_Item” is set
or not, the isset() function is executed as follows:
Example
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
if (isset($_COOKIE["Auction_Ite"]))
{
echo "Auction Item is a " . $_COOKIE["Auction_Item"];
}
else
{
echo "No items for auction.";
}
?>
</body>
</html>
Delete a Cookie
• To delete a cookie, use the setcookie() function with an
expiration date in the past:
• <?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
What is a PHP Session?
• When you work with an application, you open it, do
some changes, and then you close it.
• The computer knows who you are. It knows when you
start the application and when you end.
• But on the internet there is one problem: the web
server does not know who you are or what you do,
because the HTTP address doesn't maintain state.
Cont.
• Session variables solve this problem by storing
user information to be used across multiple
pages. By default, session variables last until the
user closes the browser.
• So; Session variables hold information about one
single user, and are available to all pages in one
application.
Start a PHP Session
• A session is started with
the session_start() function.
• Session variables are set with the PHP global
variable: $_SESSION.
• <?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Get PHP Session Variable Values
• <?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
Cont.
• Another way to show all the session variable values for a
user session is to run the following code:
• <?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>
Destroy a PHP Session
• To remove all global session variables and destroy the
session, use session_unset() and session_destroy():
• <?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>
END

More Related Content

What's hot

Origins and evolution of HTML and XHTML
Origins and evolution of HTML and XHTMLOrigins and evolution of HTML and XHTML
Origins and evolution of HTML and XHTMLHowpk
 
javaScript.ppt
javaScript.pptjavaScript.ppt
javaScript.pptsentayehu
 
Netty @Apple: Large Scale Deployment/Connectivity
Netty @Apple: Large Scale Deployment/ConnectivityNetty @Apple: Large Scale Deployment/Connectivity
Netty @Apple: Large Scale Deployment/ConnectivityC4Media
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event EmittersTheCreativedev Blog
 
JavaScript Lecture notes.pptx
JavaScript Lecture notes.pptxJavaScript Lecture notes.pptx
JavaScript Lecture notes.pptxNishaRohit6
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to phpAnjan Banda
 
Web Server - Internet Applications
Web Server - Internet ApplicationsWeb Server - Internet Applications
Web Server - Internet Applicationssandra sukarieh
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOMMindy McAdams
 
Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Gheyath M. Othman
 
Node.js Event Emitter
Node.js Event EmitterNode.js Event Emitter
Node.js Event EmitterEyal Vardi
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageAniruddha Chakrabarti
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQLArti Parab Academics
 
Authentication: Cookies vs JWTs and why you’re doing it wrong
Authentication: Cookies vs JWTs and why you’re doing it wrongAuthentication: Cookies vs JWTs and why you’re doing it wrong
Authentication: Cookies vs JWTs and why you’re doing it wrongDerek Perkins
 

What's hot (20)

Html media
Html mediaHtml media
Html media
 
Origins and evolution of HTML and XHTML
Origins and evolution of HTML and XHTMLOrigins and evolution of HTML and XHTML
Origins and evolution of HTML and XHTML
 
PHP Basic & Variables
PHP Basic & VariablesPHP Basic & Variables
PHP Basic & Variables
 
javaScript.ppt
javaScript.pptjavaScript.ppt
javaScript.ppt
 
Netty @Apple: Large Scale Deployment/Connectivity
Netty @Apple: Large Scale Deployment/ConnectivityNetty @Apple: Large Scale Deployment/Connectivity
Netty @Apple: Large Scale Deployment/Connectivity
 
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
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event Emitters
 
JavaScript Lecture notes.pptx
JavaScript Lecture notes.pptxJavaScript Lecture notes.pptx
JavaScript Lecture notes.pptx
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
Web Server - Internet Applications
Web Server - Internet ApplicationsWeb Server - Internet Applications
Web Server - Internet Applications
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOM
 
CSS notes
CSS notesCSS notes
CSS notes
 
Bootstrap grids
Bootstrap gridsBootstrap grids
Bootstrap grids
 
Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1
 
Node.js Event Emitter
Node.js Event EmitterNode.js Event Emitter
Node.js Event Emitter
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
 
Authentication: Cookies vs JWTs and why you’re doing it wrong
Authentication: Cookies vs JWTs and why you’re doing it wrongAuthentication: Cookies vs JWTs and why you’re doing it wrong
Authentication: Cookies vs JWTs and why you’re doing it wrong
 

Similar to PHP COOKIES AND SESSIONS

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
 
lecture 12.pptx
lecture 12.pptxlecture 12.pptx
lecture 12.pptxITNet
 
19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptxssuser4a97d3
 
Php file upload, cookies & session
Php file upload, cookies & sessionPhp file upload, cookies & session
Php file upload, cookies & sessionJamshid Hashimi
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introductionProgrammer Blog
 
PHP - Getting good with cookies
PHP - Getting good with cookiesPHP - Getting good with cookies
PHP - Getting good with cookiesFirdaus Adib
 
PHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdfPHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdfHumphreyOwuor1
 
Php 07-cookies-sessions
Php 07-cookies-sessionsPhp 07-cookies-sessions
Php 07-cookies-sessionsYUSRA FERNANDO
 
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
 
Maximize your Cache for No Cash
Maximize your Cache for No CashMaximize your Cache for No Cash
Maximize your Cache for No CashYorick Phoenix
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessionssalissal
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and SessionsNisa Soomro
 
Lt local storage
Lt local storageLt local storage
Lt local storageYuzu Saijo
 

Similar to PHP COOKIES AND SESSIONS (20)

Php cookies
Php cookiesPhp cookies
Php cookies
 
Sessions and cookies
Sessions and cookiesSessions and cookies
Sessions and cookies
 
Cookies & Session
Cookies & SessionCookies & Session
Cookies & Session
 
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
 
lecture 12.pptx
lecture 12.pptxlecture 12.pptx
lecture 12.pptx
 
Introduction to php web programming - sessions and cookies
Introduction to php   web programming - sessions and cookiesIntroduction to php   web programming - sessions and cookies
Introduction to php web programming - sessions and cookies
 
Manish
ManishManish
Manish
 
19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx
 
Php file upload, cookies & session
Php file upload, cookies & sessionPhp file upload, cookies & session
Php file upload, cookies & session
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introduction
 
PHP - Getting good with cookies
PHP - Getting good with cookiesPHP - Getting good with cookies
PHP - Getting good with cookies
 
PHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdfPHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdf
 
Php 07-cookies-sessions
Php 07-cookies-sessionsPhp 07-cookies-sessions
Php 07-cookies-sessions
 
Session and Cookies
Session and CookiesSession and Cookies
Session and Cookies
 
cookies.ppt
cookies.pptcookies.ppt
cookies.ppt
 
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
 
Maximize your Cache for No Cash
Maximize your Cache for No CashMaximize your Cache for No Cash
Maximize your Cache for No Cash
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
 
Lt local storage
Lt local storageLt local storage
Lt local storage
 

Recently uploaded

History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 

Recently uploaded (20)

History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 

PHP COOKIES AND SESSIONS

  • 2. Contents • Cookies and Sessions • Describe the stateless model • Explain the concepts of maintaining state with sessions • Create and Read data from sessions
  • 3.
  • 4. What is a Cookie? • A cookie is often used to identify a user. • A cookie is a small file that the server embeds on the user's computer. • Each time the same computer requests a page with a browser, it will send the cookie too. • With PHP, you can both create and retrieve cookie values.
  • 5. • Cookies are primarily used to store the user’s browsing history.
  • 6. Create Cookies With PHP • A cookie is created with the setcookie() function. • Syntax: setcookie(name, value, expire, path, domain, security); • Parameters: The setcookie() function requires six arguments in general which are:
  • 7. Parameters: • Name: It is used to set the name of the cookie. • Value: It is used to set the value of the cookie. • Expire: It is used to set the expiry timestamp of the cookie after which the cookie can’t be accessed. • Path: It is used to specify the path on the server for which the cookie will be available. • Domain: It is used to specify the domain for which the cookie is available. • Security: It is used to indicate that the cookie should be sent only if a secure HTTPS connection exists.
  • 8. Cont. • The following example creates a cookie named "user" with the value "John Doe". • The cookie will expire after 30 days (86400 * 30). • The "/" means that the cookie is available in entire website (otherwise, select the directory you prefer). • We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). • We also use the isset() function to find out if the cookie is set:
  • 9. Operations that can be performed on Cookies in PHP:
  • 10. Creating Cookies: • Creating a cookie named Auction_Item and assigning the value Luxury Car to it. • The cookie will expire after 2 days(2 days * 24 hours * 60 mins * 60 seconds).
  • 11. Example <?php $cookie_name = "user"; $cookie_value = "John Doe"; setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 30 day ?> <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>
  • 12. Checking Whether a Cookie Is Set Or Not • It is always advisable to check whether a cookie is set or not before accessing its value. • Therefore to check whether a cookie is set or not, the PHP isset() function is used. • To check whether a cookie “Auction_Item” is set or not, the isset() function is executed as follows:
  • 13. Example <!DOCTYPE html> <?php setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60); ?> <html> <body> <?php if (isset($_COOKIE["Auction_Ite"])) { echo "Auction Item is a " . $_COOKIE["Auction_Item"]; } else { echo "No items for auction."; } ?> </body> </html>
  • 14. Delete a Cookie • To delete a cookie, use the setcookie() function with an expiration date in the past: • <?php // set the expiration date to one hour ago setcookie("user", "", time() - 3600); ?> <html> <body> <?php echo "Cookie 'user' is deleted."; ?> </body> </html>
  • 15. What is a PHP Session? • When you work with an application, you open it, do some changes, and then you close it. • The computer knows who you are. It knows when you start the application and when you end. • But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn't maintain state.
  • 16. Cont. • Session variables solve this problem by storing user information to be used across multiple pages. By default, session variables last until the user closes the browser. • So; Session variables hold information about one single user, and are available to all pages in one application.
  • 17. Start a PHP Session • A session is started with the session_start() function. • Session variables are set with the PHP global variable: $_SESSION.
  • 18. • <?php // Start the session session_start(); ?> <!DOCTYPE html> <html> <body> <?php // Set session variables $_SESSION["favcolor"] = "green"; $_SESSION["favanimal"] = "cat"; echo "Session variables are set."; ?> </body> </html>
  • 19. Get PHP Session Variable Values • <?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php // Echo session variables that were set on previous page echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>"; echo "Favorite animal is " . $_SESSION["favanimal"] . "."; ?> </body> </html>
  • 20. Cont. • Another way to show all the session variable values for a user session is to run the following code: • <?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php print_r($_SESSION); ?> </body> </html>
  • 21. Destroy a PHP Session • To remove all global session variables and destroy the session, use session_unset() and session_destroy(): • <?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php // remove all session variables session_unset(); // destroy the session session_destroy(); ?> </body> </html>
  • 22. END