Lecture 26 - Cookies

And Sessions....

Administrivia

Exploration session

If you were pre approved for the alternate ES and still want credit, you have until tomorrow

Exploration Session 4 with Shuowei Li on Thursday 5/31 5:30pm in MGH 241.

CP 7 showcase is up

HW 6 due today (resources.zip has 2 more books if you want to try)

In the home stretch! CP 9 (was 10) announced, due Tuesday 5/29!

CAUSE Catalyst survey in email

Review

HTTP is a stateless protocol; it simply allows a browser to request a single document from a web server

Once the document has been sent to the client, the server does not keep track of any information about what was sent (other than maybe in a log file of the transaction).

Stateful client/server interaction

Sites like amazon.com seem to "know who I am." How do they do this? How does a client uniquely identify itself to a server, and how does the server provide specific content to each client?

Today we'll learn some technologies that are used to store "state" that can then be sent between clients and servers.

What is a cookie?

  • cookie: a small amount of information stored within the computer browser
  • cookies have many uses:
    • authentication
    • user tracking
    • maintaining user preferences, shopping carts, etc.

How cookies are set and retrieved

  • Client side (JavaScript):
    • JavaScript commands can set and retrieved using document.cookie
  • Server Side (PHP):
    • when the browser requests a page, the server may send back a cookie(s) with it using setcookie()
    • if your server has previously sent any cookies to the browser, the browser will send them back on subsequent requests stored in $_COOKIE

Facts about cookies

  • Cookies are only data, not program code.
  • Cookies can have set expiration dates.
  • Cookies help websites remember who you are (and if you are logged in).
  • Cookies CAN be used to track your viewing habits on a particular site.

A "tracking cookie"

  • an advertising company can put a cookie on your machine when you visit one site, and see it when you visit another site that also uses that advertising company
  • therefore they can tell that the same person (you) visited both sites
  • can be thwarted by telling your browser not to accept "third-party cookies"

Cookies in JavaScript: setting

  • To set a cookie use document.cookie = cookieString;
  • cookieString consists of 3 semicolon separated parts (the second two are optional):
    • name / value pair. E.g., "lastItemBought=apples"
    • expiration date (by default when browser closed). E.g., "expires=Thu, 23 May 2018 12:00:00 UTC"
    • Path where cookie belongs (default is current page). E.g., "path=/"
  • If you set a cookie where the name already has a value, the old value gets overwritten.

document.cookie = "lastItemBought=apples; " +
                  "expires=Thu, 23 May 2018 12:00:00 UTC; " +
                  "path=/";
          

JavaScript (example)

Cookies in JavaScript: Retrieving

  • To get a cookie use let cookies = document.cookie;
  • This will return a semicolon separated list of all current name=value pairs
    E.g., "lastItemBought=apples; numberSiteVisitsToday=57"
  • You have to retrieve the values from the string by parsing yourself.

Cookies in JavaScript: Clearing

To delete a cookie you need to set it's expiration time to be before now


    document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
          

JavaScript (example)

Cookies in PHP: Setting


          setcookie("name", "value", expiration);
          

PHP (template)


            $expireTime = time() + 60*60*24*7; # 1 week from now
            setcookie("CouponNumber", "389752", $expireTime);
            setcookie("CouponValue", "100.00", $expireTime);
            

PHP (example)

  • setcookie must be called before any output statements (HTML blocks, print, or echo)
  • If you don't use the third parameter, the cookie expires when browser is closed (a "session cookie")

Cookies in PHP: Retrieving


          $variable = $_COOKIE["name"]; # retrieve value of the cookie
          

PHP (example)


            if (isset($_COOKIE["username"])) {
                $username = $_COOKIE["username"];
                print("Welcome back, $username.\n");
            } else {
                print("Never heard of you.\n");
            }
            print("All cookies received:\n");
            print_r($_COOKIE);
            

PHP

  • any cookies sent by client are stored in $_COOKIES associative array
  • use isset function to see whether a given cookie name exists
  • When you call setcookie, the cookie will be available in $_COOKIE on the next page load, but not the current one.

Cookies in PHP: Deleting


          setcookie("name", FALSE);
          

PHP (example)


            setcookie("CouponNumber", FALSE);
            

PHP

  • setting the cookie to FALSE erases the cookie

Sessions

What is a session?

session: an abstract concept to represent a series of HTTP requests and responses between a specific Web browser and server

HTTP doesn't support the notion of a session, but PHP does

  • sessions vs. cookies:
    • a cookie is data stored on the client
    • a session's data is stored on the server (only 1 session per client)
  • sessions are often built using cookies:
    • the only data the client stores is a cookie holding a unique session ID
    • on each page request, the client sends its session ID cookie, and the server uses this to find and retrieve the client's session data

How sessions are established

  • client's browser makes an initial request to the server
  • server notes client's IP address/browser, stores some local session data, and creates and sends a session ID back to client (as a cookie)
  • client sends that same session ID (cookie) back to server on future requests
  • server uses session ID cookie to retrieve its data for the client's session later (like a ticket given at a coat-check room)

Cookies vs. sessions

  • duration: sessions live on until the user logs out or closes the browser; cookies can live that long, or until a given fixed timeout (persistent)
  • data storage location: sessions store data on the server (other than a session ID cookie); cookies store data on the user's browser
  • security: sessions are hard for malicious users to tamper with or remove; cookies are easy
  • privacy: sessions protect private information from being seen by other users of your computer; cookies do not

Sessions in PHP: session_start


          session_start();
          

PHP

  • session_start signifies your script wants a session with the user
    • must be called at the top of your script, before any HTML output is produced
  • What does session_start do?
    • if the server hasn't seen this user before, a new session is created
    • otherwise, existing session data is loaded into $_SESSION associative array
    • you can store data in $_SESSION and retrieve it on future pages

Accessing session data


            session_start();

            $_SESSION["name"] = value; # store session data
            $variable = $_SESSION["name"]; # read session data
            if (isset($_SESSION["name"])) { # check for session data
          

PHP (template)


            session_start();

            if (isset($_SESSION["points"])) {
                $points = $_SESSION["points"];
                print("You've earned $points points.\n");
            } else {
                $_SESSION["points"] = 0; # default
            }
          

PHP

  • the $_SESSION associative array reads/stores all session data
  • use isset function to see whether a given value is in the session

Session timeout

  • previous sessions will linger unless you destroy them and regenerate the user's session ID
  • because HTTP is stateless, it is hard for the server to know when a user has finished a session
  • ideally, user explicitly logs out, but many users don't
  • client deletes session cookies when browser closes
  • server automatically cleans up old sessions after a period of time
    • old session data consumes resources and may present a security risk
    • adjustable in PHP server settings or with session_cache_expire function
    • you can explicitly delete a session by calling session_destroy