SlideShare a Scribd company logo
http://programmerblog.net
How to work with sessions and cookies in PHP
Session Handling by http://programmerblog.net
 What Is Session Handling?
 The Hypertext Transfer Protocol (HTTP) defines the rules used to transfer text, graphics, video, and all other
data via the World Wide Web
 It is a stateless protocol, meaning that each request is processed without any knowledge of any prior or
future requests
 A cookie is a small bit of information stored on a viewer's computer by his or her web browser by request
from a web page.
 The information is constantly passed in HTTP headers between the browser and web server; the browser
sends the current cookie as part of its request to the server and the server sends updates to the data back
to the user as part of its response.
 limitations on cookie size and the number of cookies allowed, and various inconveniences surrounding their
implementation, prompted developers to devise another solution: session handling.
 Session handling is essentially a clever workaround to this problem of statelessness. This
 is accomplished by assigning each site visitor a unique identifying attribute, known as the
 session ID (SID),
 Cookies
 One ingenious means for managing user information actually builds upon the original method of using a
cookie.
 When a user visits a Web site, the server stores information about the user, such as their preferences, in a
cookie and sends it to the browser, which saves it
Session Handling by http://programmerblog.net
 When a user visits a Web site, the server stores information about the user, such as their preferences, in a
cookie and sends it to the browser, which saves it
 The second method used for SID propagation simply involves appending the SID to every local URL found
within the requested page. This results in automatic SID propagation whenever the user clicks one of those
local links. This method, known as URL rewriting.
 Drawbacks
 First, URL rewriting does not allow for persistence between sessions.
 nothing stops a user from copying that URL into an e-mail and sending it to another user; as long as the
session has not expired
Session by http://programmerblog.net
 The Session-Handling Process
 PHP can be configured to autonomously control the entire session-handling process
 The very first task executed by a session-enabled page is to determine whether a valid session already
exists or a new one should be initiated.
 Configuration Directives
 Twenty-five session configuration directives are responsible for determining the behavior of PHP’s session-
handling functionality.
 session.save_handler (files, mm, sqlite, user)
 The session.save_handler directive determines how the session information will be stored.
– Default value: files
 session.save_path (string) Default value: /tmp
 If session.save_handler is set to the files storage option, then the session.save_path directive must point to
the storage directory.
 session.name (string) Default value: PHPSESSID
 session.auto_start (0|1)
 session.gc_maxlifetime (integer)
Session by http://programmerblog.net
 Starting a Session
 session_start()
 boolean session_start() –
– session_start();
 Destroying a Session
 session_unset()
 void session_unset()
 The session_unset() function erases all session variables stored in the current session,
 Note that this will not completely remove the session from the storage mechanism.
 session_destroy()
 boolean session_destroy()
 The function session_destroy() invalidates the current session by completely removing the session from the
storage mechanism.
 Retrieving and Setting the Session ID
 session_id()
 string session_id ([string sid])
 The function session_id() can both set and get the SID. If it is passed no parameter, the function
 session_id() returns the current SID.
Session by http://programmerblog.net
 session_id()
 string session_id ([string sid])
 The function session_id() can both set and get the SID. If it is passed no parameter, the function
session_id() returns the current SID.
 echo "Your session identification number is ".session_id();
 Creating and Deleting Session Variables
 It was once common practice to create and delete session variables via the functions session_register() and
session_unregister(), respectively.
 However, the preferred method involves simply setting and deleting these variable just like any other, except
that you need to refer to it in the context of the $_SESSION superglobal.
 session_start();
 $_SESSION['username'] = "jason";
 echo "Your username is ".$_SESSION['username'].".";
 unset($_SESSION['username']);
 echo "Username now set to: ".$_SESSION['username'].".";
 Encoding and Decoding Session Data
 PHP stores session data in a standardized format consisting of a single string. For example, the contents of
a session consisting of two variables, namely
 username and loggedon, is displayed here:
 username|s:5:"jason";loggedon|s:20:"Feb 16 2006 22:32:29";
Sessions by http://programmerblog.net
 Each session variable reference is separated by a semicolon, and consists of three components: the name,
length, and value.
 name|s:length:"value";
 session_encode()
 session_start();
 // Set the variables. These could be set via an HTML form, for example.
 $_SESSION['username'] = "jason";
 $_SESSION['loggedon'] = date("M d Y H:i:s");
 // Encode all session data into a single string and return the result
 $sessionVars = session_encode();
 echo $sessionVars;
 session_decode()
 session_decode($sessionVars);
 echo "User ".$_SESSION['username']." logged on at ".$_SESSION['loggedon'].".";
Cookies by http://programmerblog.net
 Cookies
 Cookies allow your applications to store a small amount of textual data (typically,
 4-6kB) on a Web client. There are a number of possible uses for cookies, although
 their most common one is maintaining session state
 To set a cookie on the client, you can use the setcookie() function:
 setcookie(“userid", “1");
 This simple function call sets a cookie called “” to a value of 1 for the remainder of the users browser
session, at which time it is automatically deleted.
 To make a cookie persist between browser sessions, you will need to provide an expiration date.
 Expiration dates are provided to setcookie() in the UNIX timestamp format (the number of seconds that have
passed since January 1, 1970)
 setcookie(“userid`", "1", time() + 86400);
 There are threemore arguments you can pass to setcookie(). They are, in order 
 path—allows you to specify a path (relative to your website’s root) where the
 cookie will be accessible; the browser will only send a cookie to pages within this path.
 domain—allows you to limit access to the cookie to pages within a specific domain or hostname; note that
you cannot set this value to a domain other than the one of the page setting the cookie (e.g.: the host
www.phparch.com can set a
 cookie for hades.phparch.com, but not for www.microsoft.com).
 • secure—this requests that the browser only send this cookie as part of its request
 headers when communicating under HTTPS.
Cookies by http://programmerblog.net

Accessing Cookie Data
 PHP places cookies in the $_COOKIE superglobal array.
 if ($_COOKIE[’hide_menu’] == 1) {
// hide menu
}
Cookie values must be scalar; of course, you can create arrays using the same array
 notation that we used for $_GET and $_POST:
 setcookie("test_cookie[0]", "foo");
 setcookie("test_cookie[1]", "bar");
 setcookie("test_cookie[2]", "bar");
 $_COOKIE[’test_cookie’] will automatically contain an array.
 You should, however, keep in mind that the amount of storage available is severely
 limited—therefore, you should keep the amount of data you store in cookies to a
 minimum, and use sessions instead.
 Deleting a Cookie
 There is no way to “delete” a cookie—primarily because you really have no control
 over how cookies are stored and managed on the client side.
setcookie with an empty string, or in pas date which will effectively reset the cookie.
 setcookie("hide_menu", false, -3600);
Cookies by http://programmerblog.net

Accessing Cookie Data
 PHP places cookies in the $_COOKIE superglobal array.
 if ($_COOKIE[’hide_menu’] == 1) {
// hide menu
}
Cookie values must be scalar; of course, you can create arrays using the same array
 notation that we used for $_GET and $_POST:
 setcookie("test_cookie[0]", "foo");
 setcookie("test_cookie[1]", "bar");
 setcookie("test_cookie[2]", "bar");
 $_COOKIE[’test_cookie’] will automatically contain an array.
 You should, however, keep in mind that the amount of storage available is severely
 limited—therefore, you should keep the amount of data you store in cookies to a
 minimum, and use sessions instead.
 Deleting a Cookie
 There is no way to “delete” a cookie—primarily because you really have no control
 over how cookies are stored and managed on the client side.
setcookie with an empty string, or in pas date which will effectively reset the cookie.
 setcookie("hide_menu", false, -3600);

More Related Content

PPTX
PHP Cookies and Sessions
PPTX
Cookie and session
PPT
PHP - Introduction to PHP Cookies and Sessions
PDF
Introduction to php web programming - sessions and cookies
PPT
PHP - Getting good with cookies
PPTX
Sessions in php
ODP
Session Management & Cookies In Php
PHP Cookies and Sessions
Cookie and session
PHP - Introduction to PHP Cookies and Sessions
Introduction to php web programming - sessions and cookies
PHP - Getting good with cookies
Sessions in php
Session Management & Cookies In Php

What's hot (20)

PPSX
Sessions and cookies
PPT
Php Sessoins N Cookies
PPSX
Php session
PPT
PPT
Cookies and sessions
PPT
PHP Cookies, Sessions and Authentication
PPTX
Session and Cookies
PPTX
Cookie & Session In ASP.NET
PPTX
Cookies and sessions
PPT
Lecture8 php page control by okello erick
PPTX
Cookies and Session
PPTX
Session php
PDF
ASP.NET-Web Programming - Sessions and Cookies
PPT
Cookies and sessions
PPTX
Cookies in PHP
PPTX
java Cookies
PPT
Manish
PPT
Web Cookies
PPTX
Cookies
Sessions and cookies
Php Sessoins N Cookies
Php session
Cookies and sessions
PHP Cookies, Sessions and Authentication
Session and Cookies
Cookie & Session In ASP.NET
Cookies and sessions
Lecture8 php page control by okello erick
Cookies and Session
Session php
ASP.NET-Web Programming - Sessions and Cookies
Cookies and sessions
Cookies in PHP
java Cookies
Manish
Web Cookies
Cookies
Ad

Viewers also liked (12)

PPT
Php - Getting good with session
PDF
Session and Cookie
PPTX
Php session 3 Important topics
PPT
Chapter 08 php advance
PPTX
Php string function
PPTX
Cookies!
PPTX
Cookies PowerPoint
PPTX
Introduction to Web Architecture
ODP
Session por nieves
PDF
Slides For Operating System Concepts By Silberschatz Galvin And Gagne
Php - Getting good with session
Session and Cookie
Php session 3 Important topics
Chapter 08 php advance
Php string function
Cookies!
Cookies PowerPoint
Introduction to Web Architecture
Session por nieves
Slides For Operating System Concepts By Silberschatz Galvin And Gagne
Ad

Similar to Php ssession - cookies -introduction (20)

PDF
PHP-Cookies-Sessions.pdf
PPTX
Authentication in Svelte using cookies.pptx
PPTX
PHP COOKIES AND SESSIONS
PPTX
19_JavaScript - Storage_Cookies-tutorial .pptx
PPT
Session,cookies
PPT
season management in php (WT)
PDF
Jsp session tracking
PDF
S8-Session Managment
PPT
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
PPT
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
PPT
PDF
4.4 PHP Session
PPTX
PHP SESSIONS & COOKIE.pptx
PPTX
Session tracking In Java
PPTX
4 php-advanced
PDF
Cookies and sessions
PPTX
lecture 12.pptx
PPTX
Session tracking in servlets
PDF
Sea surfing in asp.net mvc
PDF
Web app development_cookies_sessions_14
PHP-Cookies-Sessions.pdf
Authentication in Svelte using cookies.pptx
PHP COOKIES AND SESSIONS
19_JavaScript - Storage_Cookies-tutorial .pptx
Session,cookies
season management in php (WT)
Jsp session tracking
S8-Session Managment
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
4.4 PHP Session
PHP SESSIONS & COOKIE.pptx
Session tracking In Java
4 php-advanced
Cookies and sessions
lecture 12.pptx
Session tracking in servlets
Sea surfing in asp.net mvc
Web app development_cookies_sessions_14

Recently uploaded (20)

PDF
AI in Product Development-omnex systems
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
ai tools demonstartion for schools and inter college
PDF
System and Network Administraation Chapter 3
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
CHAPTER 2 - PM Management and IT Context
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PPTX
Introduction to Artificial Intelligence
PPTX
Essential Infomation Tech presentation.pptx
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
medical staffing services at VALiNTRY
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
L1 - Introduction to python Backend.pptx
AI in Product Development-omnex systems
Understanding Forklifts - TECH EHS Solution
ai tools demonstartion for schools and inter college
System and Network Administraation Chapter 3
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
2025 Textile ERP Trends: SAP, Odoo & Oracle
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
CHAPTER 2 - PM Management and IT Context
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
VVF-Customer-Presentation2025-Ver1.9.pptx
Introduction to Artificial Intelligence
Essential Infomation Tech presentation.pptx
Operating system designcfffgfgggggggvggggggggg
Odoo Companies in India – Driving Business Transformation.pdf
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
wealthsignaloriginal-com-DS-text-... (1).pdf
medical staffing services at VALiNTRY
Which alternative to Crystal Reports is best for small or large businesses.pdf
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
L1 - Introduction to python Backend.pptx

Php ssession - cookies -introduction

  • 2. Session Handling by http://programmerblog.net  What Is Session Handling?  The Hypertext Transfer Protocol (HTTP) defines the rules used to transfer text, graphics, video, and all other data via the World Wide Web  It is a stateless protocol, meaning that each request is processed without any knowledge of any prior or future requests  A cookie is a small bit of information stored on a viewer's computer by his or her web browser by request from a web page.  The information is constantly passed in HTTP headers between the browser and web server; the browser sends the current cookie as part of its request to the server and the server sends updates to the data back to the user as part of its response.  limitations on cookie size and the number of cookies allowed, and various inconveniences surrounding their implementation, prompted developers to devise another solution: session handling.  Session handling is essentially a clever workaround to this problem of statelessness. This  is accomplished by assigning each site visitor a unique identifying attribute, known as the  session ID (SID),  Cookies  One ingenious means for managing user information actually builds upon the original method of using a cookie.  When a user visits a Web site, the server stores information about the user, such as their preferences, in a cookie and sends it to the browser, which saves it
  • 3. Session Handling by http://programmerblog.net  When a user visits a Web site, the server stores information about the user, such as their preferences, in a cookie and sends it to the browser, which saves it  The second method used for SID propagation simply involves appending the SID to every local URL found within the requested page. This results in automatic SID propagation whenever the user clicks one of those local links. This method, known as URL rewriting.  Drawbacks  First, URL rewriting does not allow for persistence between sessions.  nothing stops a user from copying that URL into an e-mail and sending it to another user; as long as the session has not expired
  • 4. Session by http://programmerblog.net  The Session-Handling Process  PHP can be configured to autonomously control the entire session-handling process  The very first task executed by a session-enabled page is to determine whether a valid session already exists or a new one should be initiated.  Configuration Directives  Twenty-five session configuration directives are responsible for determining the behavior of PHP’s session- handling functionality.  session.save_handler (files, mm, sqlite, user)  The session.save_handler directive determines how the session information will be stored. – Default value: files  session.save_path (string) Default value: /tmp  If session.save_handler is set to the files storage option, then the session.save_path directive must point to the storage directory.  session.name (string) Default value: PHPSESSID  session.auto_start (0|1)  session.gc_maxlifetime (integer)
  • 5. Session by http://programmerblog.net  Starting a Session  session_start()  boolean session_start() – – session_start();  Destroying a Session  session_unset()  void session_unset()  The session_unset() function erases all session variables stored in the current session,  Note that this will not completely remove the session from the storage mechanism.  session_destroy()  boolean session_destroy()  The function session_destroy() invalidates the current session by completely removing the session from the storage mechanism.  Retrieving and Setting the Session ID  session_id()  string session_id ([string sid])  The function session_id() can both set and get the SID. If it is passed no parameter, the function  session_id() returns the current SID.
  • 6. Session by http://programmerblog.net  session_id()  string session_id ([string sid])  The function session_id() can both set and get the SID. If it is passed no parameter, the function session_id() returns the current SID.  echo "Your session identification number is ".session_id();  Creating and Deleting Session Variables  It was once common practice to create and delete session variables via the functions session_register() and session_unregister(), respectively.  However, the preferred method involves simply setting and deleting these variable just like any other, except that you need to refer to it in the context of the $_SESSION superglobal.  session_start();  $_SESSION['username'] = "jason";  echo "Your username is ".$_SESSION['username'].".";  unset($_SESSION['username']);  echo "Username now set to: ".$_SESSION['username'].".";  Encoding and Decoding Session Data  PHP stores session data in a standardized format consisting of a single string. For example, the contents of a session consisting of two variables, namely  username and loggedon, is displayed here:  username|s:5:"jason";loggedon|s:20:"Feb 16 2006 22:32:29";
  • 7. Sessions by http://programmerblog.net  Each session variable reference is separated by a semicolon, and consists of three components: the name, length, and value.  name|s:length:"value";  session_encode()  session_start();  // Set the variables. These could be set via an HTML form, for example.  $_SESSION['username'] = "jason";  $_SESSION['loggedon'] = date("M d Y H:i:s");  // Encode all session data into a single string and return the result  $sessionVars = session_encode();  echo $sessionVars;  session_decode()  session_decode($sessionVars);  echo "User ".$_SESSION['username']." logged on at ".$_SESSION['loggedon'].".";
  • 8. Cookies by http://programmerblog.net  Cookies  Cookies allow your applications to store a small amount of textual data (typically,  4-6kB) on a Web client. There are a number of possible uses for cookies, although  their most common one is maintaining session state  To set a cookie on the client, you can use the setcookie() function:  setcookie(“userid", “1");  This simple function call sets a cookie called “” to a value of 1 for the remainder of the users browser session, at which time it is automatically deleted.  To make a cookie persist between browser sessions, you will need to provide an expiration date.  Expiration dates are provided to setcookie() in the UNIX timestamp format (the number of seconds that have passed since January 1, 1970)  setcookie(“userid`", "1", time() + 86400);  There are threemore arguments you can pass to setcookie(). They are, in order  path—allows you to specify a path (relative to your website’s root) where the  cookie will be accessible; the browser will only send a cookie to pages within this path.  domain—allows you to limit access to the cookie to pages within a specific domain or hostname; note that you cannot set this value to a domain other than the one of the page setting the cookie (e.g.: the host www.phparch.com can set a  cookie for hades.phparch.com, but not for www.microsoft.com).  • secure—this requests that the browser only send this cookie as part of its request  headers when communicating under HTTPS.
  • 9. Cookies by http://programmerblog.net  Accessing Cookie Data  PHP places cookies in the $_COOKIE superglobal array.  if ($_COOKIE[’hide_menu’] == 1) { // hide menu } Cookie values must be scalar; of course, you can create arrays using the same array  notation that we used for $_GET and $_POST:  setcookie("test_cookie[0]", "foo");  setcookie("test_cookie[1]", "bar");  setcookie("test_cookie[2]", "bar");  $_COOKIE[’test_cookie’] will automatically contain an array.  You should, however, keep in mind that the amount of storage available is severely  limited—therefore, you should keep the amount of data you store in cookies to a  minimum, and use sessions instead.  Deleting a Cookie  There is no way to “delete” a cookie—primarily because you really have no control  over how cookies are stored and managed on the client side. setcookie with an empty string, or in pas date which will effectively reset the cookie.  setcookie("hide_menu", false, -3600);
  • 10. Cookies by http://programmerblog.net  Accessing Cookie Data  PHP places cookies in the $_COOKIE superglobal array.  if ($_COOKIE[’hide_menu’] == 1) { // hide menu } Cookie values must be scalar; of course, you can create arrays using the same array  notation that we used for $_GET and $_POST:  setcookie("test_cookie[0]", "foo");  setcookie("test_cookie[1]", "bar");  setcookie("test_cookie[2]", "bar");  $_COOKIE[’test_cookie’] will automatically contain an array.  You should, however, keep in mind that the amount of storage available is severely  limited—therefore, you should keep the amount of data you store in cookies to a  minimum, and use sessions instead.  Deleting a Cookie  There is no way to “delete” a cookie—primarily because you really have no control  over how cookies are stored and managed on the client side. setcookie with an empty string, or in pas date which will effectively reset the cookie.  setcookie("hide_menu", false, -3600);