SlideShare a Scribd company logo
1 of 28
Download to read offline
Setting Cookies



   Pengaturcaraan PHP




Pengaturcaraan PHP
Cookies are one way that a site can remember or track a user over the course
of a visit. Think of a cookie like a name tag: you tell the server your name and it
gives you a sticker to wear. Then it can know who you are by referring back to
that name tag.




                                                                                      1
To effectively program using cookies, you need to be able to accurately test
for their presence. The best way to do so is to have your Web browser ask
what to do when receiving a cookie. In such a case, the browser will prompt
you with the cookie information each time PHP attempts to send a cookie.

Different versions of different browsers on different platforms all define their
cookie handling policies in different places. To learn more about options for
popular Web browsers, click each bullet point.

Internet Explorer
Using Internet Explorer on Windows XP, choose Tools | Internet Options.
Then click the Privacy tab, followed by the Advanced button under
Settings. Click "Override automatic cookie handling" and then choose
"Prompt" for both First and Third-party Cookies.

Firefox
Using Firefox on Windows, choose Tools | Options. Then click Privacy
and expand the Cookies section. Finally, select "ask me every time" in
the Keep Cookies drop-down menu. If you are using Firefox on Mac OS
X, the steps are the same, but you must start by choosing Firefox |
Preferences.




 Pengaturcaraan PHP

   Cookies are sent via the setcookie() function:




                                                                                   2
Pengaturcaraan PHP

You can continue to send more cookies to the browser with subsequent
uses of the setcookie() function:




Pengaturcaraan PHP

  Integrate Cookie with PHP variable




                                                                       3
Pengaturcaraan PHP
header() function

Because cookies rely upon the HTTP header, you can set them in
PHP using the header() function.

It's very important to remember that the setcookie() and header()
functions must be called before any data is sent to the Web browser.




           Accessing Cookies



  Pengaturcaraan PHP




                                                                       4
Pengaturcaraan PHP
To retrieve a value from a cookie, you only need to refer to the
$_COOKIE superglobal, using the appropriate cookie name as the key
(as you would with any array). For example, to retrieve the value of the
cookie established with the line

setcookie ('username', 'Trout');

you would use

$_COOKIE['username'].




Pengaturcaraan PHP

  Check for the presence of a cookie.




                                                                           5
Pengaturcaraan PHP

Welcome the user, using the cookie.




Pengaturcaraan PHP




                                      6
Setting Cookie
          Parameters


Pengaturcaraan PHP




Pengaturcaraan PHP
Although passing just the name and value arguments to the
setcookie() function will suffice, you ought to be aware of the other
arguments available. The function can take up to four more
parameters, each of which will alter the definition of the cookie:

Expiration

Path

Domain

Secure




                                                                        7
Pengaturcaraan PHP
The expiration argument is used to set a definitive length of time for a
cookie to exist, specified in seconds since the epoch (the epoch is
midnight on January 1, 1970). If it is not set, the cookie will continue to be
functional until the user closes his or her browser.

Normally, the expiration time is determined by adding a particular number
of minutes or hours to the current moment, retrieved using the time()
function. The following line will set the expiration time of the cookie to be 1
hour (60 seconds times 60 minutes) from the current moment:




Pengaturcaraan PHP
The path and domain arguments are used to limit a cookie to a specific
folder within a Web site (the path) or to a specific host. For example, you
could restrict a cookie to exist only while a user is within the admin folder of
a domain (and the admin folder's subfolders):




                                                                                   8
Pengaturcaraan PHP




Pengaturcaraan PHP
Setting the path
Setting the path to '/' will make the cookie visible within an entire domain
(Web site).

Setting the domain
Setting the domain to '.site.com' will make the cookie visible within an
entire domain and every subdomain (www.site.com, admin.site.com,
pages. site.com, etc.).




                                                                               9
Pengaturcaraan PHP

Finally, the secure value dictates that a cookie should only be sent over a
secure HTTPS connection. A 1 indicates that a secure connection must
be used, and a 0 signifies that a standard connection is fine.




          Deleting Cookies



Pengaturcaraan PHP




                                                                              10
Pengaturcaraan PHP
The final thing to understand about using cookies is how to delete one. While
a cookie will automatically expire when the user's browser is closed or when
the expiration date/time is met, sometimes you'll want to manually delete the
cookie instead.

For example, in Web sites that have registered users and login capabilities,
you will probably want to delete any cookies when the user logs out.




  Pengaturcaraan PHP

     To delete the first_name cookie, you would code:




                                                                                11
Pengaturcaraan PHP
As an added precaution, you can also set an expiration date that's in the past.




 Pengaturcaraan PHP




                                                                                  12
Pengaturcaraan PHP




    Setting Session
    Variables


Pengaturcaraan PHP




                      13
Pengaturcaraan PHP
Another method of making data available to
multiple pages of a Web site is to use
sessions. The premise of a session is that
data is stored on the server, not in the Web
browser, and a session identifier is used to
locate a particular user's record (session
data). This session identifier is normally
stored in the user's Web browser via a
cookie, but the sensitive data itself — like the
user's ID, name, and so on — always
remains on the server.




Pengaturcaraan PHP
Sessions in PHP requires a temporary directory on the server where
PHP can store the session data. For Unix and Mac OS X users, this
isn't a problem, as the /tmp directory is available explicitly for
purposes such as this. For Windows users, you also do not need to
do anything special as of version 4.3.6 of PHP. But if you are
running Windows and an earlier version of PHP, you must configure
the server. Here's how:


Create a new folder on your server, such as C:temp.
Make sure that Everyone (or just the Web server user, if you know
that value) can read and write to this folder.
Edit your php.ini file, setting the value of session.save_path to this
folder (C:temp).
Restart the Web server.




                                                                         14
The most important rule with respect to sessions is that each page that will
use them must begin by calling the session_start() function. This function
tells PHP to either begin a new session or access an existing one.

The first time this function is used, session_start() will attempt to send a
cookie with a name of PHPSESSID (the session name) and a value of
something like a61f8670baa8e90a30c878df89a2074b (32 hexadecimal
letters, the session ID). Because of this attempt to send a cookie,
session_start() must be called before any data is sent to the Web browser,
as is the case when using the setcookie() and header() functions.

Once the session has been started, values can be registered to the session
using the following:




 Pengaturcaraan PHP

   Replace the setcookie() lines with these lines:




                                                                               15
Pengaturcaraan PHP

Prior to version 4.1 of PHP (when the $_SESSION superglobal became
available), session variables were set using the special session_register()
function. The syntax was

session_start();
$name = 'Jessica';
session_register('name');

It's very important to notice that the session_register() function takes the
name of a variable to register without the initial dollar sign (so name rather
than $name).

Once a session variable is registered, you can refer to is using
$HTTP_SESSION_VARS['var'].

To delete a session variable, you use the session_unregister() function.




Pengaturcaraan PHP
Using session auto_start

If you want, you can set session.auto_start in the php.ini file to 1,
making it unnecessary to use session_start() on each page.

This does put a greater toll on the server and, for that reason,
shouldn't be used without some consideration of the circumstances.




                                                                                 16
Accessing Session
           Variables


  Pengaturcaraan PHP




Pengaturcaraan PHP
For other scripts to be able to access
variables from a session that has been
started, each script must first enable sessions,
using session_start().

This function will give the current script
access to the previously started session (if it
can read the PHPSESSID value stored in the
cookie) or create a new session if it cannot (in
which case, it won't be able to access stored
values because a new session will have been
created).

To then refer to a session variable, use
$_SESSION['var'], as you would refer to any
other array. Let's try this with a script.




                                                   17
Pengaturcaraan PHP

 Add a call to the session_start() function.




Pengaturcaraan PHP

Step 3
Replace the references to $_COOKIE with $_SESSION.




                                                     18
Pengaturcaraan PHP
Viewing the session ID
If you have an application where the session data does not seem to be
accessible from one page to the next, it could be because a new session is
being created on each page.

To check for this, compare the session ID (the last few characters of the value
will suffice) to see if it is the same. You can see the session's ID by viewing the
session cookie as it is sent or by using the session_id() function:

echo session_id();

Establishing session variables
Session variables are available as soon as you've established them. So,
unlike when using cookies, you can assign a value to $_SESSION['var']
and then refer to $_SESSION['var'] later in that same script.




             Deleting Session
             Variables


   Pengaturcaraan PHP




                                                                                      19
Pengaturcaraan PHP

Whereas a cookie system only requires that another cookie be sent to
destroy the existing cookie, sessions are more demanding, since there are
both the cookie on the client and the data on the server to consider. To
delete an individual session variable, you can use the unset() function
(which works with any variable in PHP):




Pengaturcaraan PHP

To delete every session variable, reset the entire $_SESSION array:

$_SESSION = array();

Finally, to remove all of the session data from the server, use
session_destroy():

session_destroy();

Note that prior to using any of these methods, the page must begin with
session_start() so that the existing session is accessed. Let's delete a
session.




                                                                            20
Pengaturcaraan PHP
 Step 2
 Invoke the session.




Pengaturcaraan PHP

Step 4
Destroy all of the session material.




                                       21
Pengaturcaraan PHP

Deleting one variable
To delete just one session variable, use unset($_SESSION['var']).




        Changing Session
        Behavior


Pengaturcaraan PHP




                                                                    22
Setting                     Example       Meaning
session.auto_start          0             If sessions should be automatically used (0 means no).

session.cookie_domain       www.mycompa   The URL wherein the session cookie should be accessible.
                            ny.com

session.cookie_lifetime     0             How long, in seconds, the session cookie should exist (0 means for
                                          the life of the browser).

session.cookie_path         /             The domain path wherein the cookie should be accessible.


session.cookie_secure       0             Whether or not the cookie must be sent over a secure connection
                                          (0 means no).

session.gc_maxlifetime      1440          The time period in seconds a session should last.

session.name                PHPSESSID     The name given to all sessions.

session.save_path           /tmp          Where session data will be stored.

session.serialize_handler   php           What method should be used to serialize the session variables.

                                          Whether or not the session ID should be stored in a cookie (0
session.use_cookies         1
                                          means no).

                                          Whether or not the session ID must be stored in a cookie (0 means
session.use_only_cookies    0
                                          no).

                                          Whether or not PHP should add the session ID to every link in an
session.use_trans_sid       0
                                          application (0 means no).




  Pengaturcaraan PHP

  Each of these settings, except for session.use_trans_sid, can be set within
  your PHP script using the ini_set() function:

  ini_set (parameter, new_setting);

  For example, to change where PHP stores the session data, use

  ini_set ('session.save_path', '/path/to/folder');




                                                                                                               23
Pengaturcaraan PHP
To set the name of the session (perhaps to make a more user-friendly one),
you can use either ini_set() or the simpler session_name() function.




 The benefits of creating your own session name are twofold: it's marginally
 more secure and it may be better received by the end user (since the session
 name is the cookie name the end user will see).

 That being said, for session_name() to work, it must be called before every use
 of session_ start() in your entire Web application. Let's rewrite the example with
 this in mind.




 Pengaturcaraan PHP

 Sessions have the following advantages over cookies

 They are generally more secure (because the data is being retained on
 the server).

 They allow for more data to be stored.

 They can be used without cookies


 Whereas cookies have the following advantages over sessions:

 They are easier to program.

 They require less of the server.




                                                                                      24
Using Sessions without
           Cookies


  Pengaturcaraan PHP




Pengaturcaraan PHP

You can use sessions without cookies
by passing along the session name
and ID from page to page. This is
simple enough to do, but if you forget
to pass the session in only one
instance, the entire process is shot.




                                         25
Improving Session
           Security




Pengaturcaraan PHP
Storing the session ID in a cookie is
considered the more secure method of
using sessions, as opposed to passing
the session ID along in URLs or storing
it in hidden form inputs. Those
alternatives are less secure because
the session could easily be hijacked by
another user.

If a malicious user can learn another
user's session ID, he can easily trick a
server into thinking that it is his session
ID. At that point he has effectively taken
over the original user's entire session
and may have access to her data. So
storing the session ID in a cookie
makes it somewhat harder to steal.




                                              26
Pengaturcaraan PHP

One method of preventing hijacking is to store some sort of user identifier in
the session, and then to repeatedly double-check this value.
HTTP_USER_AGENT — a combination of the browser and operating system
being used — is a likely candidate for this purpose. This adds a layer of
security in that a malicious user could only hijack another user's session if he
is running the exact same browser and operating system.

For example, a login page would have the following:




Pengaturcaraan PHP
Step 3
After assigning the other session variables, store HTTP_USER_AGENT.




HTTP_USER_AGENT is part of the $_SERVER array. It will have a
value like Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET
CLR 1.1.4322). This variable is run through the md5() function, which
will turn it into a 32-character hexadecimal hash (although it's just
easier to say that the data is encrypted).




                                                                                   27
Pengaturcaraan PHP

Step 6
Change the !isset($_SESSION['user_id']) conditional to the following:




          End



 Pengaturcaraan PHP




                                                                        28

More Related Content

What's hot

What's hot (18)

Cookie and session
Cookie and sessionCookie and session
Cookie and session
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
 
Lecture8 php page control by okello erick
Lecture8 php page control by okello erickLecture8 php page control by okello erick
Lecture8 php page control by okello erick
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introduction
 
Php session 3 Important topics
Php session 3 Important topicsPhp session 3 Important topics
Php session 3 Important topics
 
PHP Cookies, Sessions and Authentication
PHP Cookies, Sessions and AuthenticationPHP Cookies, Sessions and Authentication
PHP Cookies, Sessions and Authentication
 
4.4 PHP Session
4.4 PHP Session4.4 PHP Session
4.4 PHP Session
 
OpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQLOpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQL
 
Security in php
Security in phpSecurity in php
Security in php
 
PHP
PHP PHP
PHP
 
mdpress(MarkDown Press)を使ったプレゼンテーション作成
mdpress(MarkDown Press)を使ったプレゼンテーション作成mdpress(MarkDown Press)を使ったプレゼンテーション作成
mdpress(MarkDown Press)を使ったプレゼンテーション作成
 
4 php-advanced
4 php-advanced4 php-advanced
4 php-advanced
 
Node JS
Node JSNode JS
Node JS
 
Manish
ManishManish
Manish
 
Simple Spring Memcached
Simple Spring MemcachedSimple Spring Memcached
Simple Spring Memcached
 
Install mongo db on centos
Install mongo db on centosInstall mongo db on centos
Install mongo db on centos
 
Ubuntu server guide
Ubuntu server guideUbuntu server guide
Ubuntu server guide
 

Viewers also liked (6)

Agenda 21 eu cookie seminar - david naylor - field fisher waterhouse
Agenda 21   eu cookie seminar - david naylor - field fisher waterhouseAgenda 21   eu cookie seminar - david naylor - field fisher waterhouse
Agenda 21 eu cookie seminar - david naylor - field fisher waterhouse
 
[Utsoa] Enews 4.11.2008
[Utsoa] Enews 4.11.2008[Utsoa] Enews 4.11.2008
[Utsoa] Enews 4.11.2008
 
Http only cookie
Http only cookieHttp only cookie
Http only cookie
 
Php file upload, cookies & session
Php file upload, cookies & sessionPhp file upload, cookies & session
Php file upload, cookies & session
 
2014 troop cookie manager training power point
2014 troop cookie manager training power point2014 troop cookie manager training power point
2014 troop cookie manager training power point
 
The Cookie Jar Theatre and Milton Parsons Chatsworth California
The Cookie Jar Theatre and Milton Parsons Chatsworth CaliforniaThe Cookie Jar Theatre and Milton Parsons Chatsworth California
The Cookie Jar Theatre and Milton Parsons Chatsworth California
 

Similar to Cookies and sessions

Web app development_cookies_sessions_14
Web app development_cookies_sessions_14Web app development_cookies_sessions_14
Web app development_cookies_sessions_14
Hassen Poreya
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
Sukrit Gupta
 
Crud tutorial en
Crud tutorial enCrud tutorial en
Crud tutorial en
forkgrown
 
Web Site Optimization
Web Site OptimizationWeb Site Optimization
Web Site Optimization
Sunil Patil
 
Web site optimization
Web site optimizationWeb site optimization
Web site optimization
Sunil Patil
 

Similar to Cookies and sessions (20)

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-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdfPHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdf
 
Sessions and cookies
Sessions and cookiesSessions and cookies
Sessions and cookies
 
Web app development_cookies_sessions_14
Web app development_cookies_sessions_14Web app development_cookies_sessions_14
Web app development_cookies_sessions_14
 
PHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSPHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONS
 
Php 07-cookies-sessions
Php 07-cookies-sessionsPhp 07-cookies-sessions
Php 07-cookies-sessions
 
Session,cookies
Session,cookiesSession,cookies
Session,cookies
 
PHP SESSIONS & COOKIE.pptx
PHP SESSIONS & COOKIE.pptxPHP SESSIONS & COOKIE.pptx
PHP SESSIONS & COOKIE.pptx
 
Cookies and Session
Cookies and SessionCookies and Session
Cookies and Session
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
Sessions n cookies
Sessions n cookiesSessions n cookies
Sessions n cookies
 
Cake php
Cake phpCake php
Cake php
 
lecture 12.pptx
lecture 12.pptxlecture 12.pptx
lecture 12.pptx
 
Php sessions
Php sessionsPhp sessions
Php sessions
 
Ph
PhPh
Ph
 
Crud tutorial en
Crud tutorial enCrud tutorial en
Crud tutorial en
 
Drupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case StudyDrupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case Study
 
Web Site Optimization
Web Site OptimizationWeb Site Optimization
Web Site Optimization
 
Web site optimization
Web site optimizationWeb site optimization
Web site optimization
 
FP512 Cookies sessions
FP512 Cookies sessionsFP512 Cookies sessions
FP512 Cookies sessions
 

More from salissal

Error handling and debugging
Error handling and debuggingError handling and debugging
Error handling and debugging
salissal
 
Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sql
salissal
 
Web application security
Web application securityWeb application security
Web application security
salissal
 
Developing web applications
Developing web applicationsDeveloping web applications
Developing web applications
salissal
 
Programming with php
Programming with phpProgramming with php
Programming with php
salissal
 
Dynamic website
Dynamic websiteDynamic website
Dynamic website
salissal
 

More from salissal (8)

Error handling and debugging
Error handling and debuggingError handling and debugging
Error handling and debugging
 
Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sql
 
My sql
My sqlMy sql
My sql
 
Web application security
Web application securityWeb application security
Web application security
 
Developing web applications
Developing web applicationsDeveloping web applications
Developing web applications
 
Programming with php
Programming with phpProgramming with php
Programming with php
 
Basic php
Basic phpBasic php
Basic php
 
Dynamic website
Dynamic websiteDynamic website
Dynamic website
 

Recently uploaded

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
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
QucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 

Recently uploaded (20)

How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
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
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 

Cookies and sessions

  • 1. Setting Cookies Pengaturcaraan PHP Pengaturcaraan PHP Cookies are one way that a site can remember or track a user over the course of a visit. Think of a cookie like a name tag: you tell the server your name and it gives you a sticker to wear. Then it can know who you are by referring back to that name tag. 1
  • 2. To effectively program using cookies, you need to be able to accurately test for their presence. The best way to do so is to have your Web browser ask what to do when receiving a cookie. In such a case, the browser will prompt you with the cookie information each time PHP attempts to send a cookie. Different versions of different browsers on different platforms all define their cookie handling policies in different places. To learn more about options for popular Web browsers, click each bullet point. Internet Explorer Using Internet Explorer on Windows XP, choose Tools | Internet Options. Then click the Privacy tab, followed by the Advanced button under Settings. Click "Override automatic cookie handling" and then choose "Prompt" for both First and Third-party Cookies. Firefox Using Firefox on Windows, choose Tools | Options. Then click Privacy and expand the Cookies section. Finally, select "ask me every time" in the Keep Cookies drop-down menu. If you are using Firefox on Mac OS X, the steps are the same, but you must start by choosing Firefox | Preferences. Pengaturcaraan PHP Cookies are sent via the setcookie() function: 2
  • 3. Pengaturcaraan PHP You can continue to send more cookies to the browser with subsequent uses of the setcookie() function: Pengaturcaraan PHP Integrate Cookie with PHP variable 3
  • 4. Pengaturcaraan PHP header() function Because cookies rely upon the HTTP header, you can set them in PHP using the header() function. It's very important to remember that the setcookie() and header() functions must be called before any data is sent to the Web browser. Accessing Cookies Pengaturcaraan PHP 4
  • 5. Pengaturcaraan PHP To retrieve a value from a cookie, you only need to refer to the $_COOKIE superglobal, using the appropriate cookie name as the key (as you would with any array). For example, to retrieve the value of the cookie established with the line setcookie ('username', 'Trout'); you would use $_COOKIE['username']. Pengaturcaraan PHP Check for the presence of a cookie. 5
  • 6. Pengaturcaraan PHP Welcome the user, using the cookie. Pengaturcaraan PHP 6
  • 7. Setting Cookie Parameters Pengaturcaraan PHP Pengaturcaraan PHP Although passing just the name and value arguments to the setcookie() function will suffice, you ought to be aware of the other arguments available. The function can take up to four more parameters, each of which will alter the definition of the cookie: Expiration Path Domain Secure 7
  • 8. Pengaturcaraan PHP The expiration argument is used to set a definitive length of time for a cookie to exist, specified in seconds since the epoch (the epoch is midnight on January 1, 1970). If it is not set, the cookie will continue to be functional until the user closes his or her browser. Normally, the expiration time is determined by adding a particular number of minutes or hours to the current moment, retrieved using the time() function. The following line will set the expiration time of the cookie to be 1 hour (60 seconds times 60 minutes) from the current moment: Pengaturcaraan PHP The path and domain arguments are used to limit a cookie to a specific folder within a Web site (the path) or to a specific host. For example, you could restrict a cookie to exist only while a user is within the admin folder of a domain (and the admin folder's subfolders): 8
  • 9. Pengaturcaraan PHP Pengaturcaraan PHP Setting the path Setting the path to '/' will make the cookie visible within an entire domain (Web site). Setting the domain Setting the domain to '.site.com' will make the cookie visible within an entire domain and every subdomain (www.site.com, admin.site.com, pages. site.com, etc.). 9
  • 10. Pengaturcaraan PHP Finally, the secure value dictates that a cookie should only be sent over a secure HTTPS connection. A 1 indicates that a secure connection must be used, and a 0 signifies that a standard connection is fine. Deleting Cookies Pengaturcaraan PHP 10
  • 11. Pengaturcaraan PHP The final thing to understand about using cookies is how to delete one. While a cookie will automatically expire when the user's browser is closed or when the expiration date/time is met, sometimes you'll want to manually delete the cookie instead. For example, in Web sites that have registered users and login capabilities, you will probably want to delete any cookies when the user logs out. Pengaturcaraan PHP To delete the first_name cookie, you would code: 11
  • 12. Pengaturcaraan PHP As an added precaution, you can also set an expiration date that's in the past. Pengaturcaraan PHP 12
  • 13. Pengaturcaraan PHP Setting Session Variables Pengaturcaraan PHP 13
  • 14. Pengaturcaraan PHP Another method of making data available to multiple pages of a Web site is to use sessions. The premise of a session is that data is stored on the server, not in the Web browser, and a session identifier is used to locate a particular user's record (session data). This session identifier is normally stored in the user's Web browser via a cookie, but the sensitive data itself — like the user's ID, name, and so on — always remains on the server. Pengaturcaraan PHP Sessions in PHP requires a temporary directory on the server where PHP can store the session data. For Unix and Mac OS X users, this isn't a problem, as the /tmp directory is available explicitly for purposes such as this. For Windows users, you also do not need to do anything special as of version 4.3.6 of PHP. But if you are running Windows and an earlier version of PHP, you must configure the server. Here's how: Create a new folder on your server, such as C:temp. Make sure that Everyone (or just the Web server user, if you know that value) can read and write to this folder. Edit your php.ini file, setting the value of session.save_path to this folder (C:temp). Restart the Web server. 14
  • 15. The most important rule with respect to sessions is that each page that will use them must begin by calling the session_start() function. This function tells PHP to either begin a new session or access an existing one. The first time this function is used, session_start() will attempt to send a cookie with a name of PHPSESSID (the session name) and a value of something like a61f8670baa8e90a30c878df89a2074b (32 hexadecimal letters, the session ID). Because of this attempt to send a cookie, session_start() must be called before any data is sent to the Web browser, as is the case when using the setcookie() and header() functions. Once the session has been started, values can be registered to the session using the following: Pengaturcaraan PHP Replace the setcookie() lines with these lines: 15
  • 16. Pengaturcaraan PHP Prior to version 4.1 of PHP (when the $_SESSION superglobal became available), session variables were set using the special session_register() function. The syntax was session_start(); $name = 'Jessica'; session_register('name'); It's very important to notice that the session_register() function takes the name of a variable to register without the initial dollar sign (so name rather than $name). Once a session variable is registered, you can refer to is using $HTTP_SESSION_VARS['var']. To delete a session variable, you use the session_unregister() function. Pengaturcaraan PHP Using session auto_start If you want, you can set session.auto_start in the php.ini file to 1, making it unnecessary to use session_start() on each page. This does put a greater toll on the server and, for that reason, shouldn't be used without some consideration of the circumstances. 16
  • 17. Accessing Session Variables Pengaturcaraan PHP Pengaturcaraan PHP For other scripts to be able to access variables from a session that has been started, each script must first enable sessions, using session_start(). This function will give the current script access to the previously started session (if it can read the PHPSESSID value stored in the cookie) or create a new session if it cannot (in which case, it won't be able to access stored values because a new session will have been created). To then refer to a session variable, use $_SESSION['var'], as you would refer to any other array. Let's try this with a script. 17
  • 18. Pengaturcaraan PHP Add a call to the session_start() function. Pengaturcaraan PHP Step 3 Replace the references to $_COOKIE with $_SESSION. 18
  • 19. Pengaturcaraan PHP Viewing the session ID If you have an application where the session data does not seem to be accessible from one page to the next, it could be because a new session is being created on each page. To check for this, compare the session ID (the last few characters of the value will suffice) to see if it is the same. You can see the session's ID by viewing the session cookie as it is sent or by using the session_id() function: echo session_id(); Establishing session variables Session variables are available as soon as you've established them. So, unlike when using cookies, you can assign a value to $_SESSION['var'] and then refer to $_SESSION['var'] later in that same script. Deleting Session Variables Pengaturcaraan PHP 19
  • 20. Pengaturcaraan PHP Whereas a cookie system only requires that another cookie be sent to destroy the existing cookie, sessions are more demanding, since there are both the cookie on the client and the data on the server to consider. To delete an individual session variable, you can use the unset() function (which works with any variable in PHP): Pengaturcaraan PHP To delete every session variable, reset the entire $_SESSION array: $_SESSION = array(); Finally, to remove all of the session data from the server, use session_destroy(): session_destroy(); Note that prior to using any of these methods, the page must begin with session_start() so that the existing session is accessed. Let's delete a session. 20
  • 21. Pengaturcaraan PHP Step 2 Invoke the session. Pengaturcaraan PHP Step 4 Destroy all of the session material. 21
  • 22. Pengaturcaraan PHP Deleting one variable To delete just one session variable, use unset($_SESSION['var']). Changing Session Behavior Pengaturcaraan PHP 22
  • 23. Setting Example Meaning session.auto_start 0 If sessions should be automatically used (0 means no). session.cookie_domain www.mycompa The URL wherein the session cookie should be accessible. ny.com session.cookie_lifetime 0 How long, in seconds, the session cookie should exist (0 means for the life of the browser). session.cookie_path / The domain path wherein the cookie should be accessible. session.cookie_secure 0 Whether or not the cookie must be sent over a secure connection (0 means no). session.gc_maxlifetime 1440 The time period in seconds a session should last. session.name PHPSESSID The name given to all sessions. session.save_path /tmp Where session data will be stored. session.serialize_handler php What method should be used to serialize the session variables. Whether or not the session ID should be stored in a cookie (0 session.use_cookies 1 means no). Whether or not the session ID must be stored in a cookie (0 means session.use_only_cookies 0 no). Whether or not PHP should add the session ID to every link in an session.use_trans_sid 0 application (0 means no). Pengaturcaraan PHP Each of these settings, except for session.use_trans_sid, can be set within your PHP script using the ini_set() function: ini_set (parameter, new_setting); For example, to change where PHP stores the session data, use ini_set ('session.save_path', '/path/to/folder'); 23
  • 24. Pengaturcaraan PHP To set the name of the session (perhaps to make a more user-friendly one), you can use either ini_set() or the simpler session_name() function. The benefits of creating your own session name are twofold: it's marginally more secure and it may be better received by the end user (since the session name is the cookie name the end user will see). That being said, for session_name() to work, it must be called before every use of session_ start() in your entire Web application. Let's rewrite the example with this in mind. Pengaturcaraan PHP Sessions have the following advantages over cookies They are generally more secure (because the data is being retained on the server). They allow for more data to be stored. They can be used without cookies Whereas cookies have the following advantages over sessions: They are easier to program. They require less of the server. 24
  • 25. Using Sessions without Cookies Pengaturcaraan PHP Pengaturcaraan PHP You can use sessions without cookies by passing along the session name and ID from page to page. This is simple enough to do, but if you forget to pass the session in only one instance, the entire process is shot. 25
  • 26. Improving Session Security Pengaturcaraan PHP Storing the session ID in a cookie is considered the more secure method of using sessions, as opposed to passing the session ID along in URLs or storing it in hidden form inputs. Those alternatives are less secure because the session could easily be hijacked by another user. If a malicious user can learn another user's session ID, he can easily trick a server into thinking that it is his session ID. At that point he has effectively taken over the original user's entire session and may have access to her data. So storing the session ID in a cookie makes it somewhat harder to steal. 26
  • 27. Pengaturcaraan PHP One method of preventing hijacking is to store some sort of user identifier in the session, and then to repeatedly double-check this value. HTTP_USER_AGENT — a combination of the browser and operating system being used — is a likely candidate for this purpose. This adds a layer of security in that a malicious user could only hijack another user's session if he is running the exact same browser and operating system. For example, a login page would have the following: Pengaturcaraan PHP Step 3 After assigning the other session variables, store HTTP_USER_AGENT. HTTP_USER_AGENT is part of the $_SERVER array. It will have a value like Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322). This variable is run through the md5() function, which will turn it into a 32-character hexadecimal hash (although it's just easier to say that the data is encrypted). 27
  • 28. Pengaturcaraan PHP Step 6 Change the !isset($_SESSION['user_id']) conditional to the following: End Pengaturcaraan PHP 28