SlideShare une entreprise Scribd logo
1  sur  24
Télécharger pour lire hors ligne
hasen@microcis.net July 24, 2013Hassen poreya
Trainer, Cresco Solution
Afghanistan Workforce
Development Program
Maintaining State in PHP
Cookies, Sessions
HTML – a Stateless Environment
 Stateless
 Having no information about what occurred previously.
 HTTP – Stateless
 FTP – State full
 Most modern applications maintain state, which
means that they remember what you were doing
last time you ran the application, and they
remember all your configuration settings.
 This is extremely useful because it means you can
mould the application to your working habits.
HTML – a Stateless Environment
 Each request for a new web page is processed
without any knowledge of previous pages
requested or processed.
 So how they do browse multiple pages?!
 A user ‘logs in’ to a web page. Once logged in, the user
can browse the site while maintaining their logged in
state.
Is PHP Stateless?
 Variables are destroyed as soon as the page script
finishes executing.
 The script can access the ‘referrer’, the address of
the previous page, although this can’t really be
trusted.
$_SERVER['HTTP_REFERER']
 It is possible to add data to a database / text file to
add persistent data, although this is not connected
with a particular user…
Is PHP Stateless?
 The answer is NO!
 The usual way to maintain state in PHP pages is via
the use of Sessions.
 To understand how these work, we need to have a
look at what and how cookies are.
What is a Cookie?
 A cookie is a small text file that is stored on a
user’s computer.
 Each cookie on the user’s computer is connected
to a particular domain.
 Each cookie is being used to store up to 4kB of
data.
 A maximum of 20 cookies can be stored on a
user’s PC per domain.
Example
 User sends a request for page at
www.example.com for the first time!
Example
 Server sends back the page xhtml to the browser
AND stores some data in a cookie on the user’s PC.
Example
 At the next page request for domain
www.example.com, all cookie data associated with
this domain is sent too.
Set Cookie
setcookie(name,value,expire,path,
domain,secure)
 name= cookie name
 value= data to store (string)
 expire= UNIX timestamp when the cookie expires. Default is
that cookie expires when browser is closed.
 path= Path on the server within and below which the cookie
is available on.
 domain= Domain at which the cookie is available for.
 secure= If cookie should be sent over HTTPS connection only.
Default false.
Set Cookie
setcookie(‘name’,’Robert’)
 This command will set the cookie called name on
the user’s PC containing the data Robert.
 It will be available to all pages in the same
directory or subdirectory of the page that set it
(the default path and domain).
 It will expire and be deleted when the browser is
closed (default expire).
Set Cookie
setcookie(‘age’,’20’,time()+60*60*24
*30)
 This command will set the cookie called age on the
user’s PC containing the data 20.
 It will be available to all pages in the same
directory or subdirectory of the page that set it
(the default path and domain).
 It will expire and be deleted after 30 days.
Set Cookie
setcookie(‘gender’,’male’,0,’/’)
 This command will set the cookie called gender on
the user’s PC containing the data male.
 It will be available within the entire domain that
set it.
 It will expire and be deleted when the browser is
closed.
Reading Cookies
 All cookie data is available through the super
global $_COOKIE:
 $variable = $_COOKIE[‘cookie_name’]
 or
 $variable =
$HTTP_COOKIE_VARS[‘cookie_name’];
 e.g.
 $age = $_COOKIE[‘age’]
Deleting Cookies
 To remove a cookie, simply overwrite the cookie
with a new one with an expiry time in the past…
setcookie(‘cookie_name’,’’,time()-6000)
 Note that theoretically any number taken away
from the time()function should do, but due to
variations in local computer times, it is advisable
to use a day or two.
Header Request – Must be first
 As the setcookie command involves sending a
HTTP header request, it must be executed before
any xhtml is echoed to the browser, including
whitespace.
Correct Incorrect
Empty or HMTL code
Malicious Usage of Cookies
 There is a bit of a stigma attached to cookies –and
they can be maliciously used (e.g. set via 3rdparty
banner ads).
 The important thing to note is that some people
browse with them turned off.
Cookies VS Sessions
 Limited storage space
 Insecure storage client-
side
 User controlled
 Practically unlimited
space
 Reasonably securely
stored server-side
 No user control
Cookies Sessions
Starting a Session
session_start();
 Starting session always comes at the first line of
your php code.
 DO NOT start a session after any print or echo
statement!
Storing Session Data
 The $_SESSION super global array can be used
to store any session data.
 e.g.
$_SESSION[‘name’] = $name;
$_SESSION[‘age’] = $age;
Reading Session Data
 Data is simply read back from the $_SESSION
super global array.
 e.g.
$name = $_SESSION[‘name’];
$age = $_SESSION[‘age’];
Destroying/removing Session
Unset();
Unset_session();
session_destroy();
Let’s do the practice
hasen@microcis.net July 24, 2013Hassen poreya
Trainer, Cresco Solution
Any Questions!
Afghanistan Workforce
Development Program

Contenu connexe

Tendances (20)

Php session
Php sessionPhp session
Php session
 
Cookie and session
Cookie and sessionCookie and session
Cookie and session
 
Session Management & Cookies In Php
Session Management & Cookies In PhpSession Management & Cookies In Php
Session Management & Cookies In Php
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
Php Sessoins N Cookies
Php Sessoins N CookiesPhp Sessoins N Cookies
Php Sessoins N Cookies
 
Online presence for designers 2
Online presence for designers 2Online presence for designers 2
Online presence for designers 2
 
PHP - Getting good with cookies
PHP - Getting good with cookiesPHP - Getting good with cookies
PHP - Getting good with cookies
 
PHP
PHP PHP
PHP
 
My_sql_with_php
My_sql_with_phpMy_sql_with_php
My_sql_with_php
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
Session and Cookies
Session and CookiesSession and Cookies
Session and Cookies
 
PHP Cookies, Sessions and Authentication
PHP Cookies, Sessions and AuthenticationPHP Cookies, Sessions and Authentication
PHP Cookies, Sessions and Authentication
 
Session & Cookies
Session & CookiesSession & Cookies
Session & Cookies
 
Who is Afraid of Cookies?
Who is Afraid of Cookies?Who is Afraid of Cookies?
Who is Afraid of Cookies?
 
Php cookies
Php cookiesPhp cookies
Php cookies
 
Php sessions
Php sessionsPhp sessions
Php sessions
 
Remove php calls and scale your site like crazy !
Remove php calls and scale your site like crazy !Remove php calls and scale your site like crazy !
Remove php calls and scale your site like crazy !
 
Cookies
CookiesCookies
Cookies
 
Web Cookies
Web CookiesWeb Cookies
Web Cookies
 

En vedette

Web app development_html_css_03
Web app development_html_css_03Web app development_html_css_03
Web app development_html_css_03Hassen Poreya
 
Web app development_database_design_er-mapping_12
Web app development_database_design_er-mapping_12Web app development_database_design_er-mapping_12
Web app development_database_design_er-mapping_12Hassen Poreya
 
Web app development_my_sql_08
Web app development_my_sql_08Web app development_my_sql_08
Web app development_my_sql_08Hassen Poreya
 
Web app development_php_07
Web app development_php_07Web app development_php_07
Web app development_php_07Hassen Poreya
 
Web app development_php_04
Web app development_php_04Web app development_php_04
Web app development_php_04Hassen Poreya
 
Web app development_php_06
Web app development_php_06Web app development_php_06
Web app development_php_06Hassen Poreya
 
Web app development_database_design_11
Web app development_database_design_11Web app development_database_design_11
Web app development_database_design_11Hassen Poreya
 
Learn to Code with JavaScript - Choose Your Own Adventures
Learn to Code with JavaScript - Choose Your Own AdventuresLearn to Code with JavaScript - Choose Your Own Adventures
Learn to Code with JavaScript - Choose Your Own AdventuresTessa Mero
 
Web app development_php_05
Web app development_php_05Web app development_php_05
Web app development_php_05Hassen Poreya
 
Web app development_database_design_10
Web app development_database_design_10Web app development_database_design_10
Web app development_database_design_10Hassen Poreya
 
Web app development_my_sql_09
Web app development_my_sql_09Web app development_my_sql_09
Web app development_my_sql_09Hassen Poreya
 
Web app development_crud_13
Web app development_crud_13Web app development_crud_13
Web app development_crud_13Hassen Poreya
 
Web app development_html_02
Web app development_html_02Web app development_html_02
Web app development_html_02Hassen Poreya
 
Web app development_html_01
Web app development_html_01Web app development_html_01
Web app development_html_01Hassen Poreya
 

En vedette (16)

Enterprises resource planning
Enterprises resource planningEnterprises resource planning
Enterprises resource planning
 
Web app development_html_css_03
Web app development_html_css_03Web app development_html_css_03
Web app development_html_css_03
 
Web app development_database_design_er-mapping_12
Web app development_database_design_er-mapping_12Web app development_database_design_er-mapping_12
Web app development_database_design_er-mapping_12
 
Web app development_my_sql_08
Web app development_my_sql_08Web app development_my_sql_08
Web app development_my_sql_08
 
Web app development_php_07
Web app development_php_07Web app development_php_07
Web app development_php_07
 
Web app development_php_04
Web app development_php_04Web app development_php_04
Web app development_php_04
 
Web app development_php_06
Web app development_php_06Web app development_php_06
Web app development_php_06
 
Web app development_database_design_11
Web app development_database_design_11Web app development_database_design_11
Web app development_database_design_11
 
Learn to Code with JavaScript - Choose Your Own Adventures
Learn to Code with JavaScript - Choose Your Own AdventuresLearn to Code with JavaScript - Choose Your Own Adventures
Learn to Code with JavaScript - Choose Your Own Adventures
 
Web app development_php_05
Web app development_php_05Web app development_php_05
Web app development_php_05
 
Web app development_database_design_10
Web app development_database_design_10Web app development_database_design_10
Web app development_database_design_10
 
Web app development_my_sql_09
Web app development_my_sql_09Web app development_my_sql_09
Web app development_my_sql_09
 
CodeIgniter Practice
CodeIgniter PracticeCodeIgniter Practice
CodeIgniter Practice
 
Web app development_crud_13
Web app development_crud_13Web app development_crud_13
Web app development_crud_13
 
Web app development_html_02
Web app development_html_02Web app development_html_02
Web app development_html_02
 
Web app development_html_01
Web app development_html_01Web app development_html_01
Web app development_html_01
 

Similaire à Maintaining State in PHP: Cookies and Sessions

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
 
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 SESSIONSDegu8
 
Ch4(saving state with cookies and query strings)
Ch4(saving state with cookies and query strings)Ch4(saving state with cookies and query strings)
Ch4(saving state with cookies and query strings)Chhom Karath
 
javaScriptCookies.pptx
javaScriptCookies.pptxjavaScriptCookies.pptx
javaScriptCookies.pptxMattMarino13
 
Web Browsers And Other Mistakes
Web Browsers And Other MistakesWeb Browsers And Other Mistakes
Web Browsers And Other Mistakesguest2821a2
 
Javascript issues and tools in production for developers
Javascript issues and tools in production for developersJavascript issues and tools in production for developers
Javascript issues and tools in production for developersMichael Haberman
 
12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocratlinoj
 
Openam misc
Openam miscOpenam misc
Openam miscJose R
 
Web Site Optimization
Web Site OptimizationWeb Site Optimization
Web Site OptimizationSunil Patil
 
Web site optimization
Web site optimizationWeb site optimization
Web site optimizationSunil Patil
 
Drupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case StudyDrupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case Studyhernanibf
 

Similaire à Maintaining State in PHP: Cookies and Sessions (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
 
Cookies & Session
Cookies & SessionCookies & Session
Cookies & Session
 
4.4 PHP Session
4.4 PHP Session4.4 PHP Session
4.4 PHP Session
 
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
 
Ch4(saving state with cookies and query strings)
Ch4(saving state with cookies and query strings)Ch4(saving state with cookies and query strings)
Ch4(saving state with cookies and query strings)
 
javaScriptCookies.pptx
javaScriptCookies.pptxjavaScriptCookies.pptx
javaScriptCookies.pptx
 
Manish
ManishManish
Manish
 
Cookies
CookiesCookies
Cookies
 
Web Browsers And Other Mistakes
Web Browsers And Other MistakesWeb Browsers And Other Mistakes
Web Browsers And Other Mistakes
 
Javascript issues and tools in production for developers
Javascript issues and tools in production for developersJavascript issues and tools in production for developers
Javascript issues and tools in production for developers
 
12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat
 
4 php-advanced
4 php-advanced4 php-advanced
4 php-advanced
 
Download It
Download ItDownload It
Download It
 
PHP Making Web Forms
PHP Making Web FormsPHP Making Web Forms
PHP Making Web Forms
 
Openam misc
Openam miscOpenam misc
Openam misc
 
Web Site Optimization
Web Site OptimizationWeb Site Optimization
Web Site Optimization
 
Web site optimization
Web site optimizationWeb site optimization
Web site optimization
 
Drupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case StudyDrupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case Study
 

Dernier

Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 

Dernier (20)

Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 

Maintaining State in PHP: Cookies and Sessions

  • 1. hasen@microcis.net July 24, 2013Hassen poreya Trainer, Cresco Solution Afghanistan Workforce Development Program Maintaining State in PHP Cookies, Sessions
  • 2. HTML – a Stateless Environment  Stateless  Having no information about what occurred previously.  HTTP – Stateless  FTP – State full  Most modern applications maintain state, which means that they remember what you were doing last time you ran the application, and they remember all your configuration settings.  This is extremely useful because it means you can mould the application to your working habits.
  • 3. HTML – a Stateless Environment  Each request for a new web page is processed without any knowledge of previous pages requested or processed.  So how they do browse multiple pages?!  A user ‘logs in’ to a web page. Once logged in, the user can browse the site while maintaining their logged in state.
  • 4. Is PHP Stateless?  Variables are destroyed as soon as the page script finishes executing.  The script can access the ‘referrer’, the address of the previous page, although this can’t really be trusted. $_SERVER['HTTP_REFERER']  It is possible to add data to a database / text file to add persistent data, although this is not connected with a particular user…
  • 5. Is PHP Stateless?  The answer is NO!  The usual way to maintain state in PHP pages is via the use of Sessions.  To understand how these work, we need to have a look at what and how cookies are.
  • 6. What is a Cookie?  A cookie is a small text file that is stored on a user’s computer.  Each cookie on the user’s computer is connected to a particular domain.  Each cookie is being used to store up to 4kB of data.  A maximum of 20 cookies can be stored on a user’s PC per domain.
  • 7. Example  User sends a request for page at www.example.com for the first time!
  • 8. Example  Server sends back the page xhtml to the browser AND stores some data in a cookie on the user’s PC.
  • 9. Example  At the next page request for domain www.example.com, all cookie data associated with this domain is sent too.
  • 10. Set Cookie setcookie(name,value,expire,path, domain,secure)  name= cookie name  value= data to store (string)  expire= UNIX timestamp when the cookie expires. Default is that cookie expires when browser is closed.  path= Path on the server within and below which the cookie is available on.  domain= Domain at which the cookie is available for.  secure= If cookie should be sent over HTTPS connection only. Default false.
  • 11. Set Cookie setcookie(‘name’,’Robert’)  This command will set the cookie called name on the user’s PC containing the data Robert.  It will be available to all pages in the same directory or subdirectory of the page that set it (the default path and domain).  It will expire and be deleted when the browser is closed (default expire).
  • 12. Set Cookie setcookie(‘age’,’20’,time()+60*60*24 *30)  This command will set the cookie called age on the user’s PC containing the data 20.  It will be available to all pages in the same directory or subdirectory of the page that set it (the default path and domain).  It will expire and be deleted after 30 days.
  • 13. Set Cookie setcookie(‘gender’,’male’,0,’/’)  This command will set the cookie called gender on the user’s PC containing the data male.  It will be available within the entire domain that set it.  It will expire and be deleted when the browser is closed.
  • 14. Reading Cookies  All cookie data is available through the super global $_COOKIE:  $variable = $_COOKIE[‘cookie_name’]  or  $variable = $HTTP_COOKIE_VARS[‘cookie_name’];  e.g.  $age = $_COOKIE[‘age’]
  • 15. Deleting Cookies  To remove a cookie, simply overwrite the cookie with a new one with an expiry time in the past… setcookie(‘cookie_name’,’’,time()-6000)  Note that theoretically any number taken away from the time()function should do, but due to variations in local computer times, it is advisable to use a day or two.
  • 16. Header Request – Must be first  As the setcookie command involves sending a HTTP header request, it must be executed before any xhtml is echoed to the browser, including whitespace. Correct Incorrect Empty or HMTL code
  • 17. Malicious Usage of Cookies  There is a bit of a stigma attached to cookies –and they can be maliciously used (e.g. set via 3rdparty banner ads).  The important thing to note is that some people browse with them turned off.
  • 18. Cookies VS Sessions  Limited storage space  Insecure storage client- side  User controlled  Practically unlimited space  Reasonably securely stored server-side  No user control Cookies Sessions
  • 19. Starting a Session session_start();  Starting session always comes at the first line of your php code.  DO NOT start a session after any print or echo statement!
  • 20. Storing Session Data  The $_SESSION super global array can be used to store any session data.  e.g. $_SESSION[‘name’] = $name; $_SESSION[‘age’] = $age;
  • 21. Reading Session Data  Data is simply read back from the $_SESSION super global array.  e.g. $name = $_SESSION[‘name’]; $age = $_SESSION[‘age’];
  • 23. Let’s do the practice
  • 24. hasen@microcis.net July 24, 2013Hassen poreya Trainer, Cresco Solution Any Questions! Afghanistan Workforce Development Program