SlideShare une entreprise Scribd logo
1  sur  12
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
National Diploma in Information and Communication Technology
PHP :4-PHP-ADVANCED>
K72C001M07 - Web Programming
23 November 2018 K72C001M07 - Web Programming / Advanced PHP 1
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
What is a Cookie?
• A cookie is often used to identify a user.
• A cookie is a small text file that lets you store a small amount of data
(nearly 4KB) on the user's computer.
• They are typically used to keeping track of information such as
username that the site can retrieve to personalize the page when
user visit the website next time.
Note: Each time the browser requests a page to the server, all the data
in the cookie is automatically sent to the server within the request.
23 November 2018 K72C001M07 - Web Programming / Advanced PHP 2
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Setting a Cookie in PHP
The setcookie() function is used to set a cookie in PHP. Make
sure you call the setcookie() function before any output
generated by your script otherwise cookie will not set.
• Syntax
setcookie(name, value, expire, path, domain,
secure);
23 November 2018 K72C001M07 - Web Programming / Advanced PHP 3
Parameter Description
name The name of the cookie.
value The value of the cookie. Do not store sensitive information since this value is stored on the
user's computer.
expires The expiry date in UNIX timestamp format. After this time cookie will become inaccessible. The
default value is 0.
path Specify the path on the server for which the cookie will be available. If set to /, the cookie will
be available within the entire domain.
domain Specify the domain for which the cookie is available to e.g www.example.com.
secure This field, if present, indicates that the cookie should be sent only if a secure HTTPS connection
exists.
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Create a Cookie
The following example creates a cookie named "user" with the value
"John Smith". The cookie will expire after 30 days (30 days * 24 hours *
60 min * 60 sec)
//setCookie.php
<?php
$cookie_name = "user";
$cookie_value = "John Smith";
setcookie($cookie_name, $cookie_value, time() +
(86400 * 30), "/");
?>
Note: The setcookie() function must appear BEFORE the <html> tag.
23 November 2018 K72C001M07 - Web Programming / Advanced PHP 4
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Retrieve a Cookie
The PHP $_COOKIE super global variable is used to retrieve a cookie value. It typically an
associative array that contains a list of all the cookies values sent by the browser in the
current request, keyed by cookie name.
//cookie.php
<html>
<body>
<?php
$cookie_name = "user";
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>
23 November 2018 K72C001M07 - Web Programming / Advanced PHP 5
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Removing Cookies
You can delete a cookie by calling the same setcookie() function with
the cookie name and any value (such as an empty string) however this
time you need the set the expiration date in the past, as shown in the
example below:
//removeCookie.php
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() – 3600, "/");
?>
Note: You should pass exactly the same path, domain, and other
arguments that you have used when you first created the cookie in
order to ensure that the correct cookie is deleted.
23 November 2018 K72C001M07 - Web Programming / Advanced PHP 6
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
What is a PHP Session?
When you work with an application, you open it, do some changes,
and then you close it. This is much like a Session.
• 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.
• Session variables solve this problem by storing user information to be
used across multiple pages (e.g. username, favorite color, etc). By
default, session variables last until the user closes the browser.
• Session variables hold information about one single user, and are
available to all pages in one application.
Note: If you need a permanent storage, you may want to store the
data in a database.
23 November 2018 K72C001M07 - Web Programming / Advanced PHP 7
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Start a PHP Session
Before you can store any information in session variables, you must
first start up the session. To begin a new session, simply call the PHP
session_start() function. It will create a new session and generate a
unique session ID for the user.
The PHP code in the example below simply starts a new session.
<?php
// Starting session
session_start();
?>
Note: You must call the session_start() function at the beginning of the
page i.e. before any output generated by your script in the browser,
much like you do while setting the cookies with setcookie() function.
23 November 2018 K72C001M07 - Web Programming / Advanced PHP 8
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Storing Session Data
You can store all your session data as key-value pairs in the $_SESSION[]
superglobal array. The stored data can be accessed during lifetime of a
session. Consider the following script, which creates a new session and
registers two session variables.
<?php
// Starting session
session_start();
// Storing session data
$_SESSION["firstname"] = "Peter";
$_SESSION["lastname"] = "Parker";
?>
23 November 2018 K72C001M07 - Web Programming / Advanced PHP 9
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Accessing Session Data
To access the session data we set on our previous example from any other
page on the same web domain — simply recreate the session by calling
session_start() and then pass the corresponding key to the $_SESSION
associative array.
<?php
session_start();
if(!isset($_SESSION["firstname"])) {
echo "<h3>Session is not set!</h3>";
} else{
echo 'Hi, ' . $_SESSION["firstname"] . ' '
. $_SESSION["lastname"];
}
?>
Note: To access the session data in the same page there is no need to recreate
the session since it has been already started on the top of the page.
23 November 2018 K72C001M07 - Web Programming / Advanced PHP 10
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Destroying a Session
If you want to remove certain session data, simply unset the corresponding
key of the $_SESSION associative array, as shown in the following example:
<?php
session_start();
if(isset($_SESSION["lastname"])){
unset($_SESSION["lastname"]);
}
?>
However, to destroy a session completely, simply call the session_destroy()
function. This function does not need any argument and a single call destroys
all the session data.
session_unset(); //remove all session variables
session_destroy(); //destroy the session
23 November 2018 K72C001M07 - Web Programming / Advanced PHP 11
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Reference
www.w3schools.com
www.php.net
23 November 2018 K72C001M07 - Web Programming / Advanced PHP 12

Contenu connexe

Similaire à Cookies and Sessions in PHP

PHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdfPHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdfHumphreyOwuor1
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessionssalissal
 
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 ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introductionProgrammer Blog
 
Php file upload, cookies & session
Php file upload, cookies & sessionPhp file upload, cookies & session
Php file upload, cookies & sessionJamshid Hashimi
 
lecture 12.pptx
lecture 12.pptxlecture 12.pptx
lecture 12.pptxITNet
 
PHP SESSIONS & COOKIE.pptx
PHP SESSIONS & COOKIE.pptxPHP SESSIONS & COOKIE.pptx
PHP SESSIONS & COOKIE.pptxShitalGhotekar
 
Silverlight 4 @ MSDN Live
Silverlight 4 @ MSDN LiveSilverlight 4 @ MSDN Live
Silverlight 4 @ MSDN Livegoeran
 
PHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSPHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSDegu8
 
Microsoft Windows Server AppFabric
Microsoft Windows Server AppFabricMicrosoft Windows Server AppFabric
Microsoft Windows Server AppFabricMark Ginnebaugh
 
Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalabilityWim Godden
 
9780538745840 ppt ch09
9780538745840 ppt ch099780538745840 ppt ch09
9780538745840 ppt ch09Terry Yoast
 
Whatever it takes - Fixing SQLIA and XSS in the process
Whatever it takes - Fixing SQLIA and XSS in the processWhatever it takes - Fixing SQLIA and XSS in the process
Whatever it takes - Fixing SQLIA and XSS in the processguest3379bd
 
murach12.pptx
murach12.pptxmurach12.pptx
murach12.pptxxiso
 
PHP - Getting good with cookies
PHP - Getting good with cookiesPHP - Getting good with cookies
PHP - Getting good with cookiesFirdaus Adib
 

Similaire à Cookies and Sessions in PHP (20)

Cookies & Session
Cookies & SessionCookies & Session
Cookies & Session
 
PHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdfPHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdf
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
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
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introduction
 
Sessions and cookies
Sessions and cookiesSessions and cookies
Sessions and cookies
 
Php file upload, cookies & session
Php file upload, cookies & sessionPhp file upload, cookies & session
Php file upload, cookies & session
 
FP512 Cookies sessions
FP512 Cookies sessionsFP512 Cookies sessions
FP512 Cookies sessions
 
lecture 12.pptx
lecture 12.pptxlecture 12.pptx
lecture 12.pptx
 
PHP SESSIONS & COOKIE.pptx
PHP SESSIONS & COOKIE.pptxPHP SESSIONS & COOKIE.pptx
PHP SESSIONS & COOKIE.pptx
 
Silverlight 4 @ MSDN Live
Silverlight 4 @ MSDN LiveSilverlight 4 @ MSDN Live
Silverlight 4 @ MSDN Live
 
PHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSPHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONS
 
4.4 PHP Session
4.4 PHP Session4.4 PHP Session
4.4 PHP Session
 
Microsoft Windows Server AppFabric
Microsoft Windows Server AppFabricMicrosoft Windows Server AppFabric
Microsoft Windows Server AppFabric
 
Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalability
 
Sessions n cookies
Sessions n cookiesSessions n cookies
Sessions n cookies
 
9780538745840 ppt ch09
9780538745840 ppt ch099780538745840 ppt ch09
9780538745840 ppt ch09
 
Whatever it takes - Fixing SQLIA and XSS in the process
Whatever it takes - Fixing SQLIA and XSS in the processWhatever it takes - Fixing SQLIA and XSS in the process
Whatever it takes - Fixing SQLIA and XSS in the process
 
murach12.pptx
murach12.pptxmurach12.pptx
murach12.pptx
 
PHP - Getting good with cookies
PHP - Getting good with cookiesPHP - Getting good with cookies
PHP - Getting good with cookies
 

Plus de Achchuthan Yogarajah

Language Localisation of Tamil using Statistical Machine Translation - ICTer2015
Language Localisation of Tamil using Statistical Machine Translation - ICTer2015Language Localisation of Tamil using Statistical Machine Translation - ICTer2015
Language Localisation of Tamil using Statistical Machine Translation - ICTer2015Achchuthan Yogarajah
 
PADDY CULTIVATION MANAGEMENT SYSTEM
PADDY CULTIVATION MANAGEMENT  SYSTEMPADDY CULTIVATION MANAGEMENT  SYSTEM
PADDY CULTIVATION MANAGEMENT SYSTEMAchchuthan Yogarajah
 
Statistical Machine Translation for Language Localisation
Statistical Machine Translation for Language LocalisationStatistical Machine Translation for Language Localisation
Statistical Machine Translation for Language LocalisationAchchuthan Yogarajah
 
Greedy Knapsack Problem - by Y Achchuthan
Greedy Knapsack Problem  - by Y AchchuthanGreedy Knapsack Problem  - by Y Achchuthan
Greedy Knapsack Problem - by Y AchchuthanAchchuthan Yogarajah
 

Plus de Achchuthan Yogarajah (11)

Managing the design process
Managing the design processManaging the design process
Managing the design process
 
intoduction to network devices
intoduction to network devicesintoduction to network devices
intoduction to network devices
 
basic network concepts
basic network conceptsbasic network concepts
basic network concepts
 
3 php-connect-to-my sql
3 php-connect-to-my sql3 php-connect-to-my sql
3 php-connect-to-my sql
 
PHP Form Handling
PHP Form HandlingPHP Form Handling
PHP Form Handling
 
PHP-introduction
PHP-introductionPHP-introduction
PHP-introduction
 
Introduction to Web Programming
Introduction to Web Programming Introduction to Web Programming
Introduction to Web Programming
 
Language Localisation of Tamil using Statistical Machine Translation - ICTer2015
Language Localisation of Tamil using Statistical Machine Translation - ICTer2015Language Localisation of Tamil using Statistical Machine Translation - ICTer2015
Language Localisation of Tamil using Statistical Machine Translation - ICTer2015
 
PADDY CULTIVATION MANAGEMENT SYSTEM
PADDY CULTIVATION MANAGEMENT  SYSTEMPADDY CULTIVATION MANAGEMENT  SYSTEM
PADDY CULTIVATION MANAGEMENT SYSTEM
 
Statistical Machine Translation for Language Localisation
Statistical Machine Translation for Language LocalisationStatistical Machine Translation for Language Localisation
Statistical Machine Translation for Language Localisation
 
Greedy Knapsack Problem - by Y Achchuthan
Greedy Knapsack Problem  - by Y AchchuthanGreedy Knapsack Problem  - by Y Achchuthan
Greedy Knapsack Problem - by Y Achchuthan
 

Dernier

Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 

Dernier (20)

Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 

Cookies and Sessions in PHP

  • 1. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology National Diploma in Information and Communication Technology PHP :4-PHP-ADVANCED> K72C001M07 - Web Programming 23 November 2018 K72C001M07 - Web Programming / Advanced PHP 1
  • 2. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology What is a Cookie? • A cookie is often used to identify a user. • A cookie is a small text file that lets you store a small amount of data (nearly 4KB) on the user's computer. • They are typically used to keeping track of information such as username that the site can retrieve to personalize the page when user visit the website next time. Note: Each time the browser requests a page to the server, all the data in the cookie is automatically sent to the server within the request. 23 November 2018 K72C001M07 - Web Programming / Advanced PHP 2
  • 3. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Setting a Cookie in PHP The setcookie() function is used to set a cookie in PHP. Make sure you call the setcookie() function before any output generated by your script otherwise cookie will not set. • Syntax setcookie(name, value, expire, path, domain, secure); 23 November 2018 K72C001M07 - Web Programming / Advanced PHP 3 Parameter Description name The name of the cookie. value The value of the cookie. Do not store sensitive information since this value is stored on the user's computer. expires The expiry date in UNIX timestamp format. After this time cookie will become inaccessible. The default value is 0. path Specify the path on the server for which the cookie will be available. If set to /, the cookie will be available within the entire domain. domain Specify the domain for which the cookie is available to e.g www.example.com. secure This field, if present, indicates that the cookie should be sent only if a secure HTTPS connection exists.
  • 4. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Create a Cookie The following example creates a cookie named "user" with the value "John Smith". The cookie will expire after 30 days (30 days * 24 hours * 60 min * 60 sec) //setCookie.php <?php $cookie_name = "user"; $cookie_value = "John Smith"; setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); ?> Note: The setcookie() function must appear BEFORE the <html> tag. 23 November 2018 K72C001M07 - Web Programming / Advanced PHP 4
  • 5. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Retrieve a Cookie The PHP $_COOKIE super global variable is used to retrieve a cookie value. It typically an associative array that contains a list of all the cookies values sent by the browser in the current request, keyed by cookie name. //cookie.php <html> <body> <?php $cookie_name = "user"; 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> 23 November 2018 K72C001M07 - Web Programming / Advanced PHP 5
  • 6. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Removing Cookies You can delete a cookie by calling the same setcookie() function with the cookie name and any value (such as an empty string) however this time you need the set the expiration date in the past, as shown in the example below: //removeCookie.php <?php // set the expiration date to one hour ago setcookie("user", "", time() – 3600, "/"); ?> Note: You should pass exactly the same path, domain, and other arguments that you have used when you first created the cookie in order to ensure that the correct cookie is deleted. 23 November 2018 K72C001M07 - Web Programming / Advanced PHP 6
  • 7. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology What is a PHP Session? When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. • 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. • Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser. • Session variables hold information about one single user, and are available to all pages in one application. Note: If you need a permanent storage, you may want to store the data in a database. 23 November 2018 K72C001M07 - Web Programming / Advanced PHP 7
  • 8. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Start a PHP Session Before you can store any information in session variables, you must first start up the session. To begin a new session, simply call the PHP session_start() function. It will create a new session and generate a unique session ID for the user. The PHP code in the example below simply starts a new session. <?php // Starting session session_start(); ?> Note: You must call the session_start() function at the beginning of the page i.e. before any output generated by your script in the browser, much like you do while setting the cookies with setcookie() function. 23 November 2018 K72C001M07 - Web Programming / Advanced PHP 8
  • 9. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Storing Session Data You can store all your session data as key-value pairs in the $_SESSION[] superglobal array. The stored data can be accessed during lifetime of a session. Consider the following script, which creates a new session and registers two session variables. <?php // Starting session session_start(); // Storing session data $_SESSION["firstname"] = "Peter"; $_SESSION["lastname"] = "Parker"; ?> 23 November 2018 K72C001M07 - Web Programming / Advanced PHP 9
  • 10. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Accessing Session Data To access the session data we set on our previous example from any other page on the same web domain — simply recreate the session by calling session_start() and then pass the corresponding key to the $_SESSION associative array. <?php session_start(); if(!isset($_SESSION["firstname"])) { echo "<h3>Session is not set!</h3>"; } else{ echo 'Hi, ' . $_SESSION["firstname"] . ' ' . $_SESSION["lastname"]; } ?> Note: To access the session data in the same page there is no need to recreate the session since it has been already started on the top of the page. 23 November 2018 K72C001M07 - Web Programming / Advanced PHP 10
  • 11. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Destroying a Session If you want to remove certain session data, simply unset the corresponding key of the $_SESSION associative array, as shown in the following example: <?php session_start(); if(isset($_SESSION["lastname"])){ unset($_SESSION["lastname"]); } ?> However, to destroy a session completely, simply call the session_destroy() function. This function does not need any argument and a single call destroys all the session data. session_unset(); //remove all session variables session_destroy(); //destroy the session 23 November 2018 K72C001M07 - Web Programming / Advanced PHP 11
  • 12. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Reference www.w3schools.com www.php.net 23 November 2018 K72C001M07 - Web Programming / Advanced PHP 12