PHP: Saving State

  1. Overview
    1. HTTP is a stateless protocol which means that each HTTP request/response is independent of previous or subsequent HTTP requests/responses
    2. However, it is often necessary for the web server to "remember" what happened in previous transactions (e.g., purchasing something online requires multiple web pages working in tandem)
    3. PHP uses two methods to keep state: cookies and session variables
  2. Cookies
    1. A cookie is a key/value pair that stores small pieces of data in the browser
    2. Frequently used by websites to track user behavior on a website or across different websites
    3. Browsers can block cookies, but most websites (especially web applications) rely heavily on cookies to work properly
    4. Each domain has its own cookies which cannot be shared with other domains (e.g., harding.edu cannot share with google.com)
    5. Cookies can be categorized based on when they expire
      1. Persistent cookie expires at a specific time (e.g., 5 days or 10 minutes)
      2. Session cookie expires when the session expires (the browser is closed)
    6. Transmission
      1. Unexpired cookies are transmitted in every HTTP request using the Cookie header
      2. A server sets a cookie using the Set-Cookie header in the HTTP response
    7. Setting cookies
      1. Set with setcookie(cookieName, cookieValue, [expirationDate])
        // Create "session cookie" which expires when browser is closed
        setcookie("myName", "Bobby Bison");
        
        // Create "persistent cookie" which expires in 15 seconds
        setcookie("myAge", 21, time() + 15);
        
      2. Examine Network traffic in Chrome and view Response Headers
        Set-Cookie: myName=Bobby+Bison
        Set-Cookie: myAge=21; expires=Mon, 29-Oct-2018 22:32:06 GMT
        
    8. Getting cookies
      1. Get from $_COOKIES
        // Create session cookie which expires when browser is closed
        if (isset($_COOKIE["myName"])) 
        	echo "myName is $_COOKIE[myName]<br>";
        
        if (isset($_COOKIE["myAge"])) 
        	echo "myAge is $_COOKIE[myAge]";
        
      2. Examine Network traffic in Chrome and view Request Headers
        Cookie: myName=Bobby+Bison; myAge=21
        
      3. After 15 seconds have elapsed since setting the myAge cookie, the browser will no longer send it in the HTTP request
    9. Common mistakes
      1. $_COOKIES cannot be used for setting cookies!
        								// WRONG! Does not actually set any cookies on the browser
        								$_COOKIE["myName"] = "Wild Bill";
        								
      2. Calling setcookie() does not immediately put anything in $_COOKIES
        setcookie("myName") = "Susan";
        
        // ERROR! Not set until cookies are sent back from the browser!
        echo $_COOKIE["myName"];  
        
    10. View and remove cookies in Chrome
      1. Open Developer's Tools (Ctrl-Shift-I)
      2. Click Application tab
      3. Expand Cookies and select the hostname storing the cookies

        Viewing cookies in Chrome
  3. Session variables
    1. A session variable is a key/value pair that are stored on the web server
    2. Session variables are better for storing sensitive data than cookies are because the data is stored on the server
    3. Session IDs
      1. A session ID is used to uniquely identify each user's session variables on the server
        // Displays user's session ID (Example: 556mkqe25ja90lnfsskij325t0)
        echo session_id();    
        
      2. Session ID is stored in a session cookie (PHPSESSID) and sent to server in every HTTP request

        Screenshot of dev tools showing PHPSESSID cookie
      3. Warning: Hacker could impersonate you by hijacking your session if they know your session ID
    4. Setting session variables
      1. Always put session_start() at top of script
      2. Use $_SESSION to set value
        // Creates a session ID if one doesn't already exist
        session_start();
        
        $_SESSION["myName"] = "Bobby Bison";
        $_SESSION["myAge"] = 21;
        
    5. Getting session variables
      1. Always put session_start() at top of script
      2. Use $_SESSION to get value
        // Creates a session ID if one doesn't already exist
        session_start();
        
        if (isset($_SESSION["myName"]))
            echo "myName is $_SESSION[myName]<br>";
         
        if (isset($_SESSION["myAge"]))
            echo "myAge is $_SESSION[myAge]";
        
    6. Ending the session
      1. Use when there is no need for session variables (e.g., user logs out)
      2. Always put session_start() at top of script
      3. Use session_destory() to remove all variables on the server
        // Creates a session ID if one doesn't already exist
        session_start();
        
        // Clear all session variables
        session_destroy();
        
  4. More information
    1. Privacy Concerns on Cookies
    2. Third-party cookies
    3. HTML5 Local Storage