SlideShare a Scribd company logo
1 of 10
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

What's hot (20)

Sessions and cookies
Sessions and cookiesSessions and cookies
Sessions and cookies
 
Php Sessoins N Cookies
Php Sessoins N CookiesPhp Sessoins N Cookies
Php Sessoins N Cookies
 
Php session
Php sessionPhp session
Php session
 
Cookies & Session
Cookies & SessionCookies & Session
Cookies & Session
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
PHP Cookies, Sessions and Authentication
PHP Cookies, Sessions and AuthenticationPHP Cookies, Sessions and Authentication
PHP Cookies, Sessions and Authentication
 
Session and Cookies
Session and CookiesSession and Cookies
Session and Cookies
 
Cookie & Session In ASP.NET
Cookie & Session In ASP.NETCookie & Session In ASP.NET
Cookie & Session In ASP.NET
 
Cookies and sessions
Cookies and sessionsCookies and sessions
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 erick
 
Cookies and Session
Cookies and SessionCookies and Session
Cookies and Session
 
Session php
Session phpSession php
Session php
 
ASP.NET-Web Programming - Sessions and Cookies
ASP.NET-Web Programming - Sessions and CookiesASP.NET-Web Programming - Sessions and Cookies
ASP.NET-Web Programming - Sessions and Cookies
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
Cookies in PHP
Cookies in PHPCookies in PHP
Cookies in PHP
 
Sessions n cookies
Sessions n cookiesSessions n cookies
Sessions n cookies
 
java Cookies
java Cookiesjava Cookies
java Cookies
 
Manish
ManishManish
Manish
 
Web Cookies
Web CookiesWeb Cookies
Web Cookies
 
Cookies
CookiesCookies
Cookies
 

Viewers also liked

Php - Getting good with session
Php - Getting good with sessionPhp - Getting good with session
Php - Getting good with sessionFirdaus Adib
 
Session and Cookie
Session and CookieSession and Cookie
Session and CookieWarawut
 
Php session 3 Important topics
Php session 3 Important topicsPhp session 3 Important topics
Php session 3 Important topicsSpy Seat
 
Chapter 08 php advance
Chapter 08   php advanceChapter 08   php advance
Chapter 08 php advanceDhani Ahmad
 
Cookies PowerPoint
Cookies PowerPointCookies PowerPoint
Cookies PowerPointemurfield
 
Introduction to Web Architecture
Introduction to Web ArchitectureIntroduction to Web Architecture
Introduction to Web ArchitectureChamnap Chhorn
 
Slides For Operating System Concepts By Silberschatz Galvin And Gagne
Slides For Operating System Concepts By Silberschatz Galvin And GagneSlides For Operating System Concepts By Silberschatz Galvin And Gagne
Slides For Operating System Concepts By Silberschatz Galvin And Gagnesarankumar4445
 

Viewers also liked (12)

Php - Getting good with session
Php - Getting good with sessionPhp - Getting good with session
Php - Getting good with session
 
Session and Cookie
Session and CookieSession and Cookie
Session and Cookie
 
Php session 3 Important topics
Php session 3 Important topicsPhp session 3 Important topics
Php session 3 Important topics
 
Chapter 08 php advance
Chapter 08   php advanceChapter 08   php advance
Chapter 08 php advance
 
Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
 
Php string function
Php string function Php string function
Php string function
 
PHP
 PHP PHP
PHP
 
Cookies!
Cookies!Cookies!
Cookies!
 
Cookies PowerPoint
Cookies PowerPointCookies PowerPoint
Cookies PowerPoint
 
Introduction to Web Architecture
Introduction to Web ArchitectureIntroduction to Web Architecture
Introduction to Web Architecture
 
Session por nieves
Session por nievesSession por nieves
Session por nieves
 
Slides For Operating System Concepts By Silberschatz Galvin And Gagne
Slides For Operating System Concepts By Silberschatz Galvin And GagneSlides For Operating System Concepts By Silberschatz Galvin And Gagne
Slides For Operating System Concepts By Silberschatz Galvin And Gagne
 

Similar to Php ssession - cookies -introduction

PHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdfPHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdfHumphreyOwuor1
 
PHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSPHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSDegu8
 
19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptxssuser4a97d3
 
season management in php (WT)
season management in php (WT)season management in php (WT)
season management in php (WT)kunjan shah
 
Jsp session tracking
Jsp   session trackingJsp   session tracking
Jsp session trackingrvarshneyp
 
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
 
PHP SESSIONS & COOKIE.pptx
PHP SESSIONS & COOKIE.pptxPHP SESSIONS & COOKIE.pptx
PHP SESSIONS & COOKIE.pptxShitalGhotekar
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessionssalissal
 
lecture 12.pptx
lecture 12.pptxlecture 12.pptx
lecture 12.pptxITNet
 
Session tracking in servlets
Session tracking in servletsSession tracking in servlets
Session tracking in servletsvishal choudhary
 
Sea surfing in asp.net mvc
Sea surfing in asp.net mvcSea surfing in asp.net mvc
Sea surfing in asp.net mvcmagda3695
 
Web app development_cookies_sessions_14
Web app development_cookies_sessions_14Web app development_cookies_sessions_14
Web app development_cookies_sessions_14Hassen Poreya
 
javaScriptCookies.pptx
javaScriptCookies.pptxjavaScriptCookies.pptx
javaScriptCookies.pptxMattMarino13
 
07 cookies
07 cookies07 cookies
07 cookiessnopteck
 

Similar to Php ssession - cookies -introduction (20)

PHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdfPHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdf
 
PHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSPHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONS
 
19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx
 
Session,cookies
Session,cookiesSession,cookies
Session,cookies
 
season management in php (WT)
season management in php (WT)season management in php (WT)
season management in php (WT)
 
Jsp session tracking
Jsp   session trackingJsp   session tracking
Jsp session tracking
 
S8-Session Managment
S8-Session ManagmentS8-Session Managment
S8-Session Managment
 
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
 
Ecom2
Ecom2Ecom2
Ecom2
 
4.4 PHP Session
4.4 PHP Session4.4 PHP Session
4.4 PHP Session
 
PHP SESSIONS & COOKIE.pptx
PHP SESSIONS & COOKIE.pptxPHP SESSIONS & COOKIE.pptx
PHP SESSIONS & COOKIE.pptx
 
Session tracking In Java
Session tracking In JavaSession tracking In Java
Session tracking In Java
 
4 php-advanced
4 php-advanced4 php-advanced
4 php-advanced
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
lecture 12.pptx
lecture 12.pptxlecture 12.pptx
lecture 12.pptx
 
Session tracking in servlets
Session tracking in servletsSession tracking in servlets
Session tracking in servlets
 
Sea surfing in asp.net mvc
Sea surfing in asp.net mvcSea surfing in asp.net mvc
Sea surfing in asp.net mvc
 
Web app development_cookies_sessions_14
Web app development_cookies_sessions_14Web app development_cookies_sessions_14
Web app development_cookies_sessions_14
 
javaScriptCookies.pptx
javaScriptCookies.pptxjavaScriptCookies.pptx
javaScriptCookies.pptx
 
07 cookies
07 cookies07 cookies
07 cookies
 

Recently uploaded

GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 

Recently uploaded (20)

GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 

Php ssession - cookies -introduction

  • 1. http://programmerblog.net How to work with sessions and cookies in PHP
  • 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);