Storing Information: - PowerPoint PPT Presentation

1 / 59
About This Presentation
Title:

Storing Information:

Description:

Our goal as website programmers should be to make the website experience as easy ... An example of a domain is wrox.com or pawilton.com. ... – PowerPoint PPT presentation

Number of Views:57
Avg rating:3.0/5.0
Slides: 60
Provided by: ahmadrh
Category:

less

Transcript and Presenter's Notes

Title: Storing Information:


1
Storing Information Cookies
2
  • Our goal as website programmers should be to make
    the website experience as easy and pleasant for
    the user as possible. Clearly, well-designed
    pages with easily navigable layout are central to
    this, but theyre not the whole story. We can go
    one step further by learning about our users and
    using information gained about them to
    personalize the website.
  • For example, imagine a user, whose name we asked
    on the first visit, returns to our website. We
    could welcome the user back to the website by
    greeting him or her by name. Another good example
    is given by a website, such as Amazons, which
    incorporates the one-click purchasing system. By
    already knowing the users purchasing details,
    such as credit card number and delivery address,
    we can allow the user to go from viewing a book
    to buying it in just one click, making the
    likelihood of the user purchasing it that much
    greater. Also, based on information, such as the
    previous purchases and browsing patterns of the
    user, its possible to make book suggestions to
    the user.

3
  • Such personalization on websites requires that
    information about users be stored somewhere in
    between their visits to the website. Weve
    previously talked about the fact that accessing
    the users local file system from a web
    application is pretty much off limits due to
    security restrictions included in browsers.
    However, we, as website developers, can store
    small amounts of information in a special place
    on the users local disc, using what is called a
    cookie. There may be a logical reason why they
    are named cookies, but it also provides authors
    with the opportunity to make a lot of
    second-rate, food-related jokes!

4
  • Baking Our First Cookie
  • The key to cookies is the document objects
    cookie property. Using this property we can
    create and retrieve cookie data from within our
    JavaScript code.
  • We can set a cookie by setting document cookie to
    a cookie string. Well be looking in detail at
    how this cookie string is made up later in the
    chapter, but lets first create a simple example
    of a cookie and see where the information is
    stored on the users computer.

5
  • A Fresh Baked Cookie
  • The following code will set a cookie with the
    userName set as Paul, and an expiration date of
    28 December 2010.
  • Save this as FreshBakedcookie.htm.

6
  • Viewing Cookies on IE
  • Before we view the cookies, well first clear the
    temporary internet file folder for the browser
    because this will make it easier to view the
    cookies that our browser has stored. In IF,
    select internet Options from the Tools menu, as
    shown in bellow.

7
(No Transcript)
8
  • Click the Delete Files button under Temporary
    Internet files. Well be asked to confirm our
    request in another dialog box, shown in bellow.

9
  • Check the Delete all offline content check box
    and then click OK. Well be returned to the
    internet Options dialog box.
  • Lets have a look at the cookies we have
    currently residing on our machines. From the
    internet Options dialog box, click the Settings
    button next to the Delete button grouped under
    Temporary Internet files. We should see the
    dialog box shown in bellow.

10
  • Now click the View Files button, and a list of
    all the temporary pages and cookie files on your
    computer will be displayed. if you followed the
    instructions previously and deleted all temporary
    internet files, all you should see are the cookie
    files on your computer, as these are not deleted.
    The number of cookie files on your computer will
    vary

11
  • The actual cookies, their names, and their
    values, will look slightly different depending on
    your computers operating system.
  • We can delete each cookie simply by clicking it
    once, then pressing the Delete key, as you would
    with any file in Explorer. if we want to delete
    all cookies, IE 6 has a button on the general tab
    of the internet Options dialog box to delete
    cookies.
  • We can examine the contents of the cookies by
    double-clicking them

12
  • As we can see, a cookie is just a plain old text
    file. Each website, or domain name, has its own
    text file where all the cookies for that website
    are stored. in this case theres just one cookie
    currently stored for google.CO.uk.
  • Domains like amazon .Com will almost certainly
    have many cookies set. we can see the cookies
    details. Here, the name of the cookie is PREF
    the domain google.CO.uk, and it relates to the
    root directory /. The contents probably look like
    a mess of characters.

13
  • Now lets load the FreahBakedCookie.htm page into
    our IE browser This will set a cookie. Lets see
    how it has changed things by returning to the
    internet Options dialog box (by choosing the
    internet Options from the Tools menu). Click the
    Settings button, and then click View Files. My
    computer now shows the information shown in
    bellow.

14
  • Because we are creating a cookie from a web page
    that is stored on the local hard drive rather
    than a server, its domain name has been set to
    code, the directory my page was stored in.
    Obviously, this is a little artificial. in
    reality people will be loading our web pages from
    our website on the internet and not off our local
    hard drive. The internet address is based on the
    directory the FreshBakedcookie.htm file was in.
    We can also see that it expires on December 28,
    2010, as we specified when we created the cookie.
    Double-click the cookie to view its contents.
  • We can see the name we gave to the cookie at the
    left, userName, its value, Paul, and also the
    directory its applicable to. The expiration date
    is there as well its just not in an easily
    recognizable form. Note that we may sometimes
    need to close the browser and reopen it before we
    see the cookie file.

15
(No Transcript)
16
  • The Cookie String
  • When creating a cookie there are six parts we can
    set name, value, expires, path, domain, and
    security, although the latter four of these are
    optional. Well now look at each of these in
    turn.

17
  • name and value
  • The first part of the cookie string consists of
    the name and value for the cookie. The name is
    used so that we can reference the cookie at a
    later date, and the value is the information part
    of the cookie.
  • This name/value part of the cookie string is
    compulsory it sort of defeats the point of the
    cookie if you dont store a name or value because
    storing information is what cookies are all
    about. You should make sure that this part comes
    first in the cookie string.
  • The value for the cookie is a primitive string,
    although of course the string can hold number
    characters if it is numerical data that we want
    to store. if we are storing text, certain
    characters, such as semi-colons, cannot be used
    inside the value, unless we use a special
    encoding, which well see later. in the case of
    semicolons, this is because they are used to
    separate the different parts of the cookie within
    the cookie string.

18
  • In the following line of code, we set a cookie
    with the name userName and the value Paul.
  • This cookie has a very limited lifespan. By
    lifespan, we mean the length of time the
    information will continue to exist. if we dont
    set an expiration date, a cookie will expire when
    the user closes the browser. The next time the
    user opens the browser the cookie will be gone.
    This is fine if we just want to store information
    for the life of a user session, which is a single
    visit by the user to our website. However, if we
    want to ensure that our cookie is available for
    longer, we must set its expiration date, which
    well look at next.

19
  • expires
  • If we want a cookie to exist for longer than just
    a single user session, we need to set an
    expiration date using the second part of the
    cookie string, expires, as follows
  • The cookie set by the previous line of code will
    remain available for future use right up until
    December 28, 2010. Note that the format of the
    expiration date is very important, especially for
    IE browsers. it should be the same format it is
    given by the toGMTstring () method. This method
    is similar to the toUTCstring () method that we
    saw in Chapter 9.

20
  • In practice, well probably use the Date object
    to get the current date, and then set a cookie to
    expire three or six months after this date.
    Otherwise, were going to need to rewrite our
    pages on December 28,2010.For example, we could
    write the following
  • This will create a new cookie called UserName
    with the value of Paul and it will expire 6
    months from the current date. Note that other
    factors can cause a cookie to expire before its
    expiration date, such as the user deleting the
    cookie or the upper cookie limit being reached.

21
  • path
  • Well find that 99 percent of the time, we will
    only need to set the name, value and expires
    parts of a cookie. However, at times the other
    three parts, such as the path part that we are
    looking at here, need to be set. The final two
    parts, domain and secure, are for more advanced
    use beyond the scope of a beginners book, but
    well look at them briefly just for completeness.
  • We know that cookies are specific to a certain
    path, but what if we want to view our cookies
    from two different paths on our server? Say for
    example we have an online store at
  • www.mywebsite.com/ mystore/ but we subdivide the
    store into subdirectories, such as /Books and
    /Games. Now lets imagine that our checkout is in
    the directory www.mywebsite.com/mystore/Checkout.
    Any cookies set in the /Books and /Games
    directories wont be visible to each other or
    pages in the /Checknut directory. To get around
    this we can either set cookies only in the
    /mystore directory, since these can be read by
    that directory and any of its subdirectories, or
    we can use the path part of the cookie string to
    specify that the path of the cookie is /mystore
    even if its being set in the /Games or /Books or
    /Checkout subdirectories.

22
  • For example, we could do this like so
  • Now, the cookie will be available to all
    directories on the domain it is set from. if the
    website is just one of many at that domain, its
    best not to do this because everyone else will
    also have access to our cookie information.
  • Its important to note that while Windows
    computers dont have case-sensitive directory
    names, many other operating systems do. For
    example, if our website is on a Unix- or
    Linux-based server, the path property will be
    case sensitive.

23
  • domain
  • The fourth part of the cookie string is the
    domain. An example of a domain is wrox.com or
    pawilton.com. Like the path part of the cookie
    string, the domain part is optional and its
    unlikely that youll find yourself using it very
    often.
  • By default, cookies are available only to pages
    in the domain they were set in. For example, if
    we have our first website running on a server
    with the domain MyPersonalwebSite.MyDomain.com
    and we have a second website running under
    MyBusinesswebsite . MyDomain.com, a cookie set in
    one website will not be available to pages
    accessed using the other domain name, and vice
    versa.
  • Most of the time this is exactly what we want,
    but if it is not, we can use the domain part of
    the cookie string to specify that a cookie is
    available to all subdomains of the specified
    domain.

24
  • For example, the following sets a cookie that can
    be shared across both subdomains
  • document.cookie UserNamePaulexpiresTue,
    28 Dec 2010 000000path-/
    domain-Myflomain.com
  • Note that the domain must be the same We cant
    share www. SomeoneElsesDomain.com with
    www.MyDomain.com.

25
  • secure
  • The final part of the cookie string is the secure
    part. This is simply a Boolean value if its set
    to true the cookie will only be sent to a web
    sever that tries to retrieve it using a secure
    channel. The default value, which is false, means
    the cookie will always be sent, regardless of the
    security. This is only applicable where we have
    set up a server with SSL (Secure Sockets Layer).

26
  • Creating a Cookie
  • To make life easier for ourselves, well write a
    function that allows us to create a new cookie
    and set certain of its attributes with more ease.
    Well look at the code first and create an
    example using it shortly.

27
  • The secure and domain parts of the cookie string
    are unlikely to be needed, so we just allow the
    name, value, expires, and path parts of a cookie
    to be set by the function. if we dont want to
    set a path or expiration date, we just pass empty
    strings for those parameters. if no path is
    specified, the current directory and its
    subdirectories will be the path. if no expiration
    date is set, we just assume a date six months
    from now.
  • The first line of the function introduces the
    escape () function, which weve not seen before.

28
  • When we talked about setting the value of a
    cookie, we mentioned that certain characters
    cannot be used directly, such as a semicolon.
    (This also applies to the name of the cookie.) To
    get around this problem, we can use the built-in
    escape() and unescape() functions. The escape ()
    function converts characters that are not text or
    numbers into the hexadecimal equivalent of their
    character in the Latin-1 character set, preceded
    by a character.

29
  • For example, a space has the hexadecimal value of
    20, and the semicolon has the value of 3B. So,
    the following code produces the output shown in
    Figure 1143.
  • alert(escape(2001 a space odyssey))
  • We can see that the spaces have been converted to
    2 0, indicating that they represent an escape
    or special character rather than an actual
    character, and that 20 is the ASCII value of the
    actual character The semicolon has been converted
    to 3B, as wed expect.

30
  • As well see later, when retrieving cookie values
    we can use the unescape () function to convert
    from the encoded version to plain text.
  • Back to our function we next have an if
    statement.

31
  • This deals with the situation where an empty
    string, , has been passed for the cookieExpires
    parameter of the function. Because most of the
    time we want a cookie to last longer than the
    session its created in, we set a default value
    for expires that is six months after the current
    date.
  • Next, if a value other than an empty string ( )
    has been passed to the function for the
    cookiepath parameter, we need to add that value
    when we create the cookie. We simply put path
    in front of any value that has been passed in the
    cookiepath parameter
  • Finally on the last line we actually create the
    cookie, putting together the cookieName,
    cookieValue, cookieExpires, and cookie Path parts
    of the string.

32
  • Well be using the setcookie () function whenever
    we want to create a new cookie because it makes
    setting a cookie slightly easier than having to
    remember all the parts we want to set. More
    importantly, it can be used to set the expiration
    date to a date six months ahead of the current
    date.
  • Well now put this together in a simple example
    in which we use our setcookie () function to set
    three cookies named Name, Age, and FirstVisit. We
    then display what is in the document. cookie
    property to see how this has been affected.

33
(No Transcript)
34
  • Save the example as createcookie.htm, and then
    load it into a web browser
  • Note that all three cookies are displayed as
    name/value pairs separated by semicolons, and
    also that the expiration date is not displayed.
    if we had set the path parameter, this also would
    not have been displayed. The UserName cookie from
    a previous example is also displayed.

35
  • Getting a Cookies Value
  • In the preceding example, we used document.cookie
    to retrieve a string containing information about
    the cookies that have been set. However, this
    string has two limitations.
  • First, the cookies are retrieved in name/value
    pairs, with each individual cookie separated by a
    semicolon. The expires, path, domain, and secure
    parts of the cookie are not available to us and
    cannot be retrieved.
  • Second, the cookie property allows you to
    retrieve only all the cookies set for a
    particular path and, when hosted on a web server,
    that web server So, for example, theres no
    simple way of just getting the value of a cookie
    with the name Age. To do this well have to use
    the string manipulation techniques weve learned
    in previous chapters to cut the information we
    want out of the returned string.
  • A lot of different ways exist to get the value of
    an individual cookie, but the way well use has
    the advantage of working with all cookie-enabled
    browsers. We use the following function

36
(No Transcript)
37
  • Getting a Cookies Value
  • In the preceding example, we used document.cookie
    to retrieve a string containing information about
    the cookies that have been set. However, this
    string has two limitations.
  • First, the cookies are retrieved in name/value
    pairs, with each individual cookie separated by a
    semicolon. The expires, path, domain, and secure
    parts of the cookie are not available to us and
    cannot be retrieved.
  • Second, the cookie property allows you to
    retrieve only all the cookies set for a
    particular path and, when hosted on a web server,
    that web server So, for example, theres no
    simple way of just getting the value of a cookie
    with the name Age. To do this well have to use
    the string manipulation techniques weve learned
    in previous chapters to cut the information we
    want out of the returned string.

38
  • A lot of different ways exist to get the value of
    an individual cookie, but the way well use has
    the advantage of working with all cookie-enabled
    browsers. We use the following function

39
  • The first task of the function is to get the
    document cookie string and store it in the
    variable cookieValue.
  • Next we need to find out where the cookie with
    the name passed as a parameter to the function is
    within the cookievalue string. We use the indexof
    0 method of the String object to find this
    information, as shown in the following line.
  • The method will either return the character
    position where the individual cookie is found or
    -l if no such name, and therefore no such cookie,
    exists. We search on cookieName so that
    we dont inadvertently find cookie names or
    values containing the name that we require. For
    example, if we have xFoo, Foo, and yFoo as cookie
    names, a search for Foo without a space in front
    would match the xFoo first, which is not what we
    want!

40
  • If cookieStartsAt is -1, the cookie does not
    exist or its at the very beginning of the cookie
    string so there is no space in front of the
    cookie name. To see which of these is true, we do
    another search, this time with no space.
  • in the next if statement we check to see whether
    the cookie has been found. if it hasnt, we set
    the cookieValue variable to null.

41
  • If the cookie has been found, we get the value of
    the cookie we want from the document . cookie
    string in an else statement. We do this by
    finding the start and the end of the value part
    of that cookie. The start will be immediately
    after the equals sign following the name. So in
    the following line, we find the equals sign
    following the name of the cookie in the string by
    starting the indexof () search for an equals sign
    from the character at which the cookie name/value
    pair starts.
  • We then add one to this value to move past the
    equals sign. The end of the cookie value will
    either be at the next semicolon or at the end of
    the string, whichever comes first. We do a search
    for a semicolon, starting from the cookiestartsAt
    index in the next line.

42
  • If the cookie we are after is the last one in the
    string, there will be no semicolon and the
    cookieEndsAt variable will be -1 for no match. in
    this case we know the end of the cookie value
    must be the end of the string, so we set the
    variable cookieEndsAt to the length of the
    string.
  • We then get the cookies value using the
    substring () method to cut the value that we want
    out of the main string. Because we have encoded
    the string with the escape () function, we need
    to unescape it to get the real value, hence the
    use of the unescape () function.

43
  • Finally we return the value of the cookie to the
    calling function.
  • Now we know how to create and retrieve cookies.
    Lets use this knowledge in an example where we
    check to see if any changes have been made to a
    website since the user last visited it.
  • Well be creating two pages for this example. The
    first is the main page for a website the second
    is the page with details of new additions and
    changes to the website. A link to the second page
    will only appear on the first page if the user
    has visited the page before (that is, a cookie
    exists) but has not visited since the page was
    last updated.

44
(No Transcript)
45
(No Transcript)
46
(No Transcript)
47
  • This page needs to be saved as MainPage.htm. Note
    that it contains the two functions, setCookie ()
    and getcookievalue ( ), that we created earlier.
    Also note that the image whatsNew. gif is
    referenced by this page either create such an
    image, or retrieve the image from the code
    download.
  • Next, well just create a simple page to link to
    for the Whats New details.
  • Save this page as WhatsNew.htm.

48
  • Load MainPage.htm into a browser. The first time
    we go to the main page, there will be just a
    heading saying Welcome to my website. Obviously
    if this were a real website, it would have a bit
    more than that, but it suffices for our example.
    However, refresh the page and suddenly well see
    the page shown bellow.
  • If we click on the image, were taken to the
    whatsNew.htm page detailing all the things added
    to the website since we last visited.

49
  • How It Works
  • The whatsNew.htm page is just a simple html page
    with no script, so we will confine our attention
    to MainPage.htm. in the head of the page in the
    first script block, we declare the variable
    lastupdated.
  • Whenever we make a change to the website this
    variable needs to be changed. its currently set
    to Tue, 28 Dec 2010 just to make sure we see a
    Whats New image when we refresh the page. A
    better alternative for live pages would be the
    document.lastModified property, which returns the
    date the page was last changed.
  • The rest of the first script block contains the
    two functions getcookievalue () and setcookie ()
    that we looked at earlier These havent changed,
    so we wont discuss them in detail here.

50
  • The interesting material is in the second script
    block that is found within the body of the page.
    First we get the date of the users last visit
    stored in the LastVisit cookie using the
    getcookievalue () function.
  • if its null, the user has never been here
    before, or it has been six or more months since
    the last visit, and the cookie has expired.
    Either way, we wont put a Whats New image up
    because everything is new if the user is a first
    time visitor, or a lot has probably changed in
    the last six monthsmore than what our Whats New
    page will detail.
  • if lastvisit is not null, we need to check
    whether the user visited the site before the site
    was last updated, and if so direct the user to a
    page that shows what is new. We do this within
    the if statement.

51
  • We first create a new Date object based on the
    value of lastVisit and store that back into the
    lastvisit variable. Then, in the condition of the
    inner if statement, we compare the date of the
    users last visit with the date we last updated
    the website. if things have changed since the
    users last visit, we write the Whats New image
    to the page, so the user can click it and find
    out whats new. Note that we have used the escape
    character \ for the inside the strings that are
    written to the page because, otherwise,
    JavaScript will think they indicate the end of
    the string.

52
  • Finally, at the end of the script block, we reset
    the LastVisit cookie to todays date and time
    using the setcookie () function.

53
  • Cookie Limitations
  • You should be aware of a number of limitations
    when using cookies.
  • The first is that while all modern browsers
    support cookies, the user may have disabled them.
    in NN we can do this from the Preferences option
    on the Edit menu. The option to disable cookies
    is under Advanced on NN 4.x, and under the
    Cookies option under Advanced on NN 6. In IE its
    under internet Options on the Tools menu. Select
    the Security tab and click the Custom Level
    button. From there, a list of security options
    appears, some of which relate to the setting of
    cookies.
  • Both the functions that weve created for
    creating and getting cookies will cause no errors
    when cookies are disabled, but of course the
    value of any cookie set will be null and we need
    to make sure our code can cope with this.

54
  • We could set a default action for when cookies
    are disabled. For example, in the previous
    example, if cookies are disabled, a Whats New
    image will never appear.
  • Alternatively, we can let the user know that our
    website needs cookies to function by putting a
    message in the web page warning users.
  • Another way is to actively check to see whether
    cookies are enabled and, if not, take some action
    to cope with this, such as directing the user to
    a page with less functionality that does not need
    cookies. How do we check to see if cookies are
    enabled?
  • In the following script we set a test cookie, and
    then read back its value, if its null, we know
    cookies are disabled.

55
  • A second limitation is on the number of cookies
    we can set on the users computer for our website
    and how much information can be stored. For each
    domain and path we can store up to 20 cookies,
    and each cookie pair, that is, the name and value
    combined, must be not more than 4096 characters
    in size. its also important to be aware that all
    browsers do set some upper limit for the number
    of cookies stored. Once that limit is reached,
    often what happens is older cookies, regardless
    of expiration date, are deleted. Modern browsers
    have a 300-cookie limit, though this may vary
    between browsers.
  • To get around the 20-cookie limit, we can store
    more than one piece of information per cookie.
    This example uses multiple cookies

56
  • We could combine this information into one
    cookie, with each detail separated by a
    semicolon.
  • Because the setcookie() function escapes the
    value of the cookie, there is no confusion
    between the semicolons separating pieces of data
    in the value of the cookie, and semicolons
    separating the parts of the cookie. When we get
    the cookie value back using getcookievalue ( ),
    we just split it into its constituent parts
    however, we must remember the order we stored it
    in.

57
  • Cookie Security and 1E6
  • IE6 has introduced a new security policy for
    cookies based on the P3P recommendations made by
    the World Wide Web Consortium, or W3C for short,
    a web standards body that deals with not only
    cookies but html, XML, and various other browser
    standards. Their website is at www w3 c org and
    contains a host of information, though its far
    from being an easy read.
  • The general aim of P3P is to reassure users who
    are worried that cookies are being used to obtain
    personal information about their browsing habits.
    In IE 6 under the ToolsD1nternet Options, select
    the Privacy tab to see where we can set the level
    of privacy with regards to cookies. (See next
    Figure) Its a balance between setting it so high
    that no website will work, or too low and run the
    risk of having your browsing habits recorded and
    potentially personal data stored

58
  • Generally, by default session cookies are
    allowed, that is, cookies that last for only as
    long as the user is browsing our website. As soon
    as the user closes the browser, the session ends.
    However if we want cookies to outlast the users
    visit to our website, we need to create a privacy
    policy in line with the P3P recommendations. This
    sounds a little complex, and certainly the fine
    details of the policy can be. However, IBM has
    created software that makes creating the XML for
    the policy fairly easy. Its not cheap, but there
    is a 90-day free trial. It can be downloaded from
    www. aiphaworks.ibm. com/tech/ p3peditor.
  • Plenty of other policy creation software is
    available this just happens to be quite easy to
    use. P3PFdit is available for a much lower cost
    from http / /policyeditor. com/.

59
(No Transcript)
Write a Comment
User Comments (0)
About PowerShow.com