Cookies and Sessions - PowerPoint PPT Presentation

1 / 42
About This Presentation
Title:

Cookies and Sessions

Description:

Cookies and Sessions Cookies are useful for storing user info that should be retained from one page to the next. (Overcome the stateless nature of the web) – PowerPoint PPT presentation

Number of Views:320
Avg rating:3.0/5.0
Slides: 43
Provided by: Jason589
Category:

less

Transcript and Presenter's Notes

Title: Cookies and Sessions


1
Cookies and Sessions
  • Cookies are useful for storing user info that
    should be retained from one page to the next.
    (Overcome the stateless nature of the web)
  • Cookies are written to the clients hard drive.
  • Problems
  • User can disable cookies in the browser
  • Cookies may be viewed by other users
  • Can only store 20 cookies max 4KB.
  • Some browsers may display incorrectly unless all
    options are set in setcookie()

2
Creating a cookie
  • setcookie(name,value,expiration)
  • Eg, setcookie(fruit,banana,time()3600) The
    cookies is called fruit and has a value of
    banana it will expire 1 hr from now.
  • Eg. setcookie(username,jceddia,time()1800)
  • Cookie values are sent as part of the HTTP
    headers (transparent to user). No output should
    be sent to the browser (echo etc) until the
    cookie is set else cookie will not be set.

3
Accessing A Cookie
  • Once created,cookie values are automatically
    available to PHP scripts as a variable having the
    same name as the cookie.
  • Eg. echo the current user is username
  • Php associative array HTTP_COOKIE_VARS contain
    the value of every current cookie
  • Foreach (HTTP_COOKIE_VARS as name gtvalue)
    echo ltBRgtname gt value

4
Deleting a Cookie
  • Automatically deleted after expiration time
  • Can manually delete by setting negative time
  • setcookie(username,,time()-3600)
  • Other cookie options
  • setcookie(name,value,expire,path,domain,secure)
  • pathwhich scripts have access to cookie values?.
    By default, any script in the current server
    directory downward have access. Parent directory
    doesnt.

5
Other cookie options
  • domain by default, a cookie is only available
    to scripts on the current web server. Specify a
    domain name for other servers. NOTE that some
    browsers need at least two dots in the domain
    name (Netscape).
  • secure how cookies are sent.
  • 1 https (secure connection)
  • 0 http (normal connection) php has Mcrypt
    functions.
  • Eg.setcookie(username,jceddia,time()3600,/we
    broot,http//www.csse.monash.edu.au,0)

6
Redirection
  • Once login data is captured/validated then want
    to go to a new page.
  • Header(Location URL)
  • header("Location http//silas.cc.monash.edu.au7
    77/p-6-2.html")
  • General technique
  • Site start page login page
  • Login page validates user and set cookies
  • Redirect to new page
  • New page uses cookie data to access DB info

7
Sessions
  • What if user disables cookies? Need to store data
    on the server. This is done in session variables.
  • A session variable is a regular global variable
    that, when registered as a session variable,
    keeps its value on all pages that use PHP4
    sessions. To register a session variable, assign
    a value to a variable that is to become a session
    variable and call
  • session_register("variable_name").
  • On all subsequent pages that uses sessions (by
    calling session_start()), the variable
    variable_name will have the value assigned to it
    before it was registered as a session variable.
    Changes to the variable value will be
    automatically registered in the session and saved
    for further reference

8
Session cont.
  • A visitor accessing your web site is assigned an
    unique id, the so-called session id. This is
    either stored in a cookie on the user side or is
    propagated in the URL.
  • The session support allows you to register
    arbitrary numbers of variables to be preserved
    across requests. When a visitor accesses your
    site, PHP will check automatically (if
    session.auto_start is set to 1) or on your
    request (explicitly through session_start() or
    implicitly through session_register()) whether a
    specific session id has been sent with the
    request. If this is the case, the prior saved
    environment is recreated.
  • All registered variables are serialized after the
    request finishes. Registered variables which are
    undefined are marked as being not defined. On
    subsequent accesses, these are not defined by the
    session module unless the user defines them
    later.

9
  • The track_vars and register_globals configuration
    settings influence how the session variables get
    stored and restored.
  • Note As of PHP 4.0.3, track_vars is always
    turned on.
  • Note As of PHP 4.1.0, _SESSION is available as
    global variable just like _POST, _GET,
    _REQUEST and so on. Not like HTTP_SESSION_VARS,
    _SESSION is always global. Therefore, global
    should not be used for _SESSION.
  • If track_vars is enabled and register_globals is
    disabled, only members of the global associative
    array HTTP_SESSION_VARS can be registered as
    session variables. The restored session variables
    will only be available in the array
    HTTP_SESSION_VARS.
  • If register_globals is enabled, then all global
    variables can be registered as session variables
    and the session variables will be restored to
    corresponding global variables. Since PHP must
    know which global variables are registered as
    session variables, users must register variables
    with session_register() function while
    HTTP_SESSION_VARS/_SESSION does not need to use
    session_register().

10
  • Example 1. Registering a variable with track_vars
    enabled
  • lt?php
  • if (isset(HTTP_SESSION_VARS'count'))
    HTTP_SESSION_VARS'count'
  • else
  • HTTP_SESSION_VARS'count' 0
  • ?gt
  • Use of _SESSION (or HTTP_SESSION_VARS with PHP
    4.0.6 or less) is recommended for security and
    code readablity.
  • Disabling register_globals is recommended for
    both security and performance reason.

11
  • With _SESSION or HTTP_SESSION_VARS, there is no
    need to use session_register() /session_unregister
    ()/ session_is_registered() functions. Users can
    access session variable like a normal variable.
  • Example 2. Registering a variable with _SESSION.
  • lt?php // Use HTTP_SESSION_VARS with PHP 4.0.6 or
    less
  • if (!isset(_SESSION'count'))
  • _SESSION'count' 0
  • else _SESSION'count'
  • ?gt

12
  • Example 3. Unregistering a variable with
    _SESSION.
  • lt?php // Use HTTP_SESSION_VARS with PHP 4.0.6 or
    less unset(_SESSION'count')
  • ?gt

13
Session Ids.
  • There are two methods to propagate a session id
  • Cookies
  • URL parameter
  • The session module supports both methods. Cookies
    are optimal, but since they are not reliable
    (clients are not bound to accept them), we cannot
    rely on them. The second method embeds the
    session id directly into URLs.
  • PHP is capable of doing this transparently when
    compiled with --enable-trans-sid. If you enable
    this option, relative URIs will be changed to
    contain the session id automatically.
    Alternatively, you can use the constant SID which
    is defined, if the client did not send the
    appropriate cookie. SID is either of the form
    session_namesession_id or is an empty string.

14
Sids
  • The following example demonstrates how to
    register a variable, and how to link correctly to
    another page using SID.
  • Example 5. Counting the number of hits of a
    single user
  • lt?php
  • if (!session_is_registered('
    count'))
  • session_register('count'
    )
  • count 1
  • else
  • count
  • ?gt
  • Hello visitor, you have seen this page lt?php
    echo count ?gt times.ltpgt

15
Sids cont.
  • lt?php
  • the lt?php echo SID?gt
    (lt?SID?gt can be used if short tag is enabled)
  • is necessary to preserve
    the session id
  • in the case that the user
    has disabled cookies
  • ?gt
  • To continue, ltA HREF"nextpage.php?lt?php echo
    SID?gt"gtclick herelt/Agt
  • The lt?SID?gt is not necessary, if
    --enable-trans-sid was used to compile PHP.
    Note Non-relative URLs are
    assumed to point to external sites and hence
    don't append the SID, as it
    would be a security risk to leak the SID to a
    different server.

16
  • To implement database storage, or any other
    storage method, you will need to use
    session_set_save_handler() to create a set of
    user-level storage functions.
  • The session management system supports a number
    of configuration options which you can place in
    your php.ini file. Refer to php manual for more
    details.
  • http//www.php.net/manual/en/ref.session.php

17
Session functions
  • session_start -- Initialize session data
  • session_destroy -- Destroys all data registered
    to a session
  • session_name -- Get and/or set the current
    session name
  • session_module_name -- Get and/or set the current
    session module
  • session_save_path -- Get and/or set the current
    session save path
  • session_id -- Get and/or set the current session
    id
  • session_register -- Register one or more
    variables with the current session
  • session_unregister -- Unregister a variable from
    the current session
  • session_unset -- Free all session variables
  • session_is_registered -- Find out if a variable
    is registered in a session
  • session_get_cookie_params -- Get the session
    cookie parameters
  • session_set_cookie_params -- Set the session
    cookie parameters
  • session_decode -- Decodes session data from a
    string
  • session_encode -- Encodes the current session
    data as a string
  • session_set_save_handler -- Sets user-level
    session storage functions
  • session_cache_limiter -- Get and/or set the
    current cache limiter
  • session_cache_expire -- Return current cache
    expire
  • session_write_close -- Write session data and end
    session

18
Session_start()
  • All pages that uses PHP4 sessions must call the
    function session_start() to tell the PHP4 engine
    to load session related information into memory.
    The session_start() function tries to find the
    session id in the cookie field or the request
    parameters for the current HTTP request. If it
    cannot find the session id, a new session is
    created.

19
Session_register()
  • The first example (page1.php)
  • lt?php
  • session_start()
  • my_session_variable "some value"
  • session_register("my_session_variable")
  • ?gt
  • //may also use _SESSIONmy_session_var'
    somevalue

20
  • What this does is that it registers the variable
    my_session_variable as a session variable. This
    means that the variable will be alive (keep it's
    value) across page-accesses, as long as you call
    the session_start() function on all pages that
    need access to the my_session_variable variable. 
  • Example 2 (page2.php)
  •  
  • lt?php
  • session_start()
  • print "Value of 'my_session_variable'
  • my_session_variable"
  • ?gt

21
  • Using session variables for authentication in
    conjunction with a database . Create a login-page
    gives the user a userid and password form and
    posts to another PHP page (this example uses
    mysql)  
  • lt?php
  • session_start()
  • if (userid password)
  • res mysql_query("SELECT userid FROM users
    WHERE userid'userid' AND password'password'")
  • if(mysql_num_rows(res) ! 0)
  • verified_user userid
  • session_register("verified_user")
  • Header("Location your_main_page.php")
  • ?gt  
  • Now, on 'your_main_page.php', you call
    session_start() and then you can check the
    verified_user variable to see if the user has
    been authenticated (and who he is). Other uses
    for session variables, easing database load by
    caching certain values in the session rather than
    reading them from the database on each page
    access.

22
Example 2 register user
  • Just to make explicit what probably others have
    already figured out from the documentation, only
    global variables can be stored in the session.
    Any variable that you manipulate in a function
    must be declared global if you
    want to store it in the session, and any
    session variable that you need access to must be
    declared global. For example,
  • session_start()
  • function confirmUserLogin (postLoginUrl) //
    Function to check login
  • // To get access to this session var,
    I must declare it global.
  • global
    session_userID
  • if (!IsSet(session_us
    erID))
  • session_register('s
    ession_post_login_page')
  • // To set this session var, I must declare
    it global.
  • global
    session_post_login_page
  • session_post_login
    _page postLoginUrl
  • redirect("/login/")

23
Example register user cont.
  • // Function to set a user's ID after login
  • function setUserLogin
    (userID)
  • // Again, must
    declare session_userID
  • // global so that I
    can set it.
  • global
    session_userID
  • session_userID
    userID
  • // Function to retrieve
    the stored userID
  • function getUserLogin ()
  • // Again, must
    declare variable global
  • // in order to access
    it.
  • global
    session_userID
  • return(session_userID
    )
  • Editor's Note Use of HTTP_SESSION_VARS/_SESSION
    is recommended

24
Destroying a session
  • lt?php
  • // Initialize the session.
  • // If you are using session_name("something"),
  • // don't forget it now!
  • session_start()
  • // Unset all of the session variables.
  • session_unset()
  • // Finally, destroy the session.
  • session_destroy()
  • ?gt

25
Destroying a session - _SESSION
  • lt?php
  • // Initialize the session. If you are using
    session_name("something"), don't forget it now!
  • session_start()
  • // Unset all of the session
    variables.
  • _SESSION array()
  • // Finally, destroy
    the session.
  • session_destroy()
  • ?gt

26
Templates
  • Templates allow the separation of php code from
    html
  • Useful on large sites where graphic designers
    manipulate html and php programmers write code
  • ltHTMLgtltHEADgt
  • ltTITLEgt Sample Templatelt/TITLEgtlt/HEADgt
  • ltBODYgt
  • The answer to todays question is ANSWER.
  • lt/BODYgtlt/HTMLgt
  • ANSWER is a template variable which is
    evaluated when the page is fetched

27
To Use Templates - do
  • Create a template file
  • Create a php script that fills in the template by
  • Instantiate a template object (template.inc)
  • Associate a template variable with the template
    file (.tpl extension)
  • Assign values to template variables (
  • Parse the template variable associated with the
    template file
  • Print the value of the template containing the
    result.

28
  • Assume that there is a template in the
    /home/mydir/mytemplates/ named MyTemplate.tpl
    that has some text that reads something like
    this  
  • Congratulations! You won a new some_color Book!
  •  "some_color" has curly braces around it. The
    curly braces indicate that some_color is a
    template variable. A PHP script that will load
    the template, insert the value of the PHP
    variable my_color where the some_color
    template variable tag is, and then output the new
    text. If my_color happens to be set to "blue",
    the final output should look like
  •  
  • Congratulations! You won a new blue Book!

29
Template Example cont.
  • lt?php
  • include "template.inc"  
  • my_color "blue" // we'll use this later 
  • t new Template("/home/mydir/mytemplates/")
  • // create a template object named t
  • t-gtset_file("MyFileHandle","MyTemplate.tpl")
  • // set MyFileHandle our template file
  • t-gtset_var("some_color",my_color)
  • // set template variable some_color
    my_color value
  • t-gtparse("MyOutput","MyFileHandle")
  • // set template variable MyOutput parsed
    file
  • t-gtp("MyOutput") // output the value of
    MyOutput (our parsed data) 
  • ?gt

30
Template Example cont.
  • NOTE The path ("/home/mydir/mytemplates/") in
    the Template constructor call sets the root path
    where your templates are located, but if you
    leave it out it defaults to the same directory as
    your PHP script.
  • Nothing is output to the web server until
    p("MyOutput") is called, which outputs the
  • final parsed text.

31
Nested Templates
  • A feature of the parse() function is that the
    MyOutput handle that it created is actually a
    template variable, just as some_color is a
    template variable. So if you have another
    template with a MyOutput tag, when you parse
    that second template, all of the MyOutput tags
    will be replaced with the parsed text from
    MyOutput. This lets you embed the text of one
    template file into another template. So, we could
    have another template called wholePage.tpl that
    contains the text  
  • Sorry you didn't win. But if you had won, we
    would have told you MyOutput
  • And after wholePage.tpl is parsed, the final
    output would be  
  • Sorry you didn't win. But if you had won, we
    would have told you Congratulations! You won a
    new blue Book!

32
Nested template example
  • lt?php
  • t new Template("/home/mydir/mytemplates/")
  • // These three lines are the same as the first
    example
  • t-gtset_file("MyFileHandle","MyTemplate.tpl")
  • t-gtset_var("some_color",my_color)
  • t-gtparse("MyOutput","MyFileHandle")
  • // (Note that we don't call p()
  • //here, so nothing gets output yet.)
  • // Now parse a second template
  • t-gtset_file("WholeHandle","wholePage.tpl")
  • // wholePage.ihtml has "MyOutput" in it
  • t-gtparse("MyFinalOutput","WholeHandle")
  • // All MyOutput's get replaced
  • t-gtp("MyFinalOutput")
  • // output the value of MyFinalOutput
  • ?gt

33
Template Array parameters
  • parse() and p() can be combined using the shorter
    function pparse() replacing the last two lines
    with
  • lt?php pparse("MyFinalOutput","SecondHandle") ?gt
  • The functions set_file() and set_var() can also
    accept multiple sets of values at a time by
    passing an array of handle/value pairs. Here are
    examples  
  • lt?php
  •  t-gtset_file(array(
  • "pageOneHandle" gt "pageone.tpl",
  • "pageTwoHandle" gt "pagetwo.tpl"))
  • t-gtset_var(array(
  • "last_name" gt "Gates",
  • "first_name" gt "Bill",
  • "net_worth" gt reallybignumber))
  •  ?gt

34
Appending Template Text
  • A third parameter that you can pass to parse()
    and pparse() if you want to append data to the
    template variable rather than overwrite it.
    Simply call parse() or pparse() with the third
    parameter as true, such as  
  • lt?php t-gtparse("MyOutput","MyFileHandle", true)
    ?gt
  •  If MyOutput already contains data, MyFileHandle
    will be parsed and appended onto the existing
    data in MyOutput. This technique is useful if you
    have a template where you want the same text to
    be repeated multiple times, such as listing
    multiple rows of results from a database query.

35
Example
  • lt?php
  • t new Template("/home/mydir/mytemplates/")
  • t-gtset_file(array(
  • "mainpage" gt "mainpage.tpl",
  • "each_element" gt "each_element.tpll"))
  • reset(myArray)
  • while (list(elementName, elementValue)
    each(myArray))
  • // Set 'value' and 'name' to each element's
    value and name
  • t-gtset_var("name",elementName)
  • t-gtset_var("value",elementValue)
  • // Append copies of each_element
  • t-gtparse("array_elements","each_element",true)
  • t-gtpparse("output","mainpage")
  • ?gt

36
Example cont.
  • This example uses two templates, mainpage.tpl and
    each_element.tpl. The mainpage.tpl template could
    look something like this  
  • ltHTMLgt
  • Here is the array
  • ltTABLEgt
  • array_elements
  • lt/TABLEgt
  • lt/HTMLgt
  •  The array_elements tag above will be replaced
    with copies of each_element.tpl, which is
    repeated for each element of the array
    (myArray). The
  • each_element.ihtml template might look like this
  •  ltTRgt ltTDgtname valuelt/TDgt lt/TRgt
  •  The result is a formatted table of the elements
    of myArray.

37
Constructing a complete web site
  • A typical web page includes elements such as
  • Headers appear at the top of the page
  • Navigation bar below the header or on LHS of
    page
  • Content in the center of the page
  • Footers at the bottom of the page
  • For consistency across the whole site it is usual
    to create a template that describes each
    element and an additional template file
    describing the way these elements are combined.

38
Example - Std.tpl
  • ltHTMLgt
  • ltHEADgt
  • ltTITLEgttitlelt/TITLEgt
  • lt/HEADgt
  • ltBODYgt
  • ltTABLE CELLPADDING"10"gt
  • ltTRgt
  • ltTD COLSPAN"2" ALIGN"LEFT"gtheaderlt/TDgt
  • lt/TRgt
  • ltTRgt
  • ltTD VALIGN"TOP" ALIGN"LEFT"gtleftnavlt/TDgt
  • ltTD VALIGN"TOP" ALIGN"LEFT"gtcontentlt/TDgt
  • lt/TRgt
  • lt/TABLEgt lt/BODYgt lt/HTMLgt

39
Example - header.tpl
  • ltTABLE CELLPADDING"5" BORDER"1" WIDTH"600"gt
  • ltTRgt
  • ltTDgt
  • ltFONT SIZE"6"gtltBgtThe Generic Web Site
    lt/Bgtlt/FONTgt
  • ltBRgt
  • lt/TRgt
  • lt/TABLEgt

40
Example - leftnav.tpl
  • ltTABLE CELLPADDING"5" BORDER"1" WIDTH"100"gt
  • ltTRgt
  • ltTDgt
  • ltA HREF"index.php"gtltBRgtHomeltBRgtltBRgt
  • ltA HREF"function1.php"gtFunction 1ltBRgtltBRgt
  • ltA HREF"function2.php"gtFunction 2ltBRgtltBRgt
  • ltA HREF"logout.php"gtltBRgtLogoutltBRgt
  • lt/TRgt
  • lt/TABLEgt

41
Example - index.tpl
  • ltFONT SIZE"7"gtWelcome to the ltBRgttitle!lt/FONTgt
  • ltBRgt
  • ltBRgt
  • This is where you'll find information about
    absolutely nothing.
  • We're so sure you won't find anything of interest
    here, we'll
  • pay you if you can show us we're wrong.

42
Example - index.php
  • lt?php
  • include 'template.inc'
  • tpl new Template('.')
  • //assume the templates are in the current
    directory
  • tpl-gtset_file(array('std' gt'std.tpl',
  • 'header' gt'header.tpl',
  • 'leftnav'gt'leftnav.tpl',
  • 'content'gt'index.tpl'))
  • tpl-gtset_var('title', 'Generic Web Site')
  • tpl-gtparse('header', 'header')
  • tpl-gtparse('leftnav', 'leftnav')
  • tpl-gtparse('content', 'content')
  • tpl-gtparse('DUMMY', 'std')
  • tpl-gtp('DUMMY')
  • ?gt
Write a Comment
User Comments (0)
About PowerShow.com