Lab 5: Sessions & More Client vs. Server Concepts

Goals

Learn about...

  1. The difference between Client vs. Server processing
  2. More JavaScript & PHP coding conventions
  3. Why sessions and server-side processing is so important.

Key Concept

While JavaScript has many useful features for processing HTML documents, server-side processing is often necessary to "remember" information, i.e., storing information temporarily or permanently. Storing information dynamically is the key in implementing web applications. The server has the ability to store information temporarily in session variable and permanently in files or databases.

Pre-lab

Pre-lab Reading

  • Textbook pp 69-95 (Textbook = Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition)

If you do not have the textbook, http://php.net is a helpful reference.

Pre-lab Activity

Refer to the Pre-lab Reading to answer the Lab 5 Quiz in Blackboard.

In-lab

Remember, if your instructor is busy helping others, call for help and make sure the instructor sees that you need help, but then go back to work. As you wait for help, try your best to solve the problem on your own by reading the textbook and web sources.

Preparation

  1. For file and folder names only use lowercase letters and never use spaces.
  2. Store all your files in your lab5 folder on the network drive

JavaScript can run locally

You do not need to upload JavaScript to the server to run it properly. For parts 1 and 2, you can test your files locally.

Part 1: JavaScript Shopping Cart

  1. Download shop.html, save it to your lab folder, view the source code in Notepad++ and test the script in Chrome to understand how it works.
  2. Add buttons for the other products. Note that you will have to pass a string literal for each product, i.e., "Mountain Dew", "Beef Jerky", etc.
  3. The alert message is annoying and it is unnecessary to have to click the View Cart Button. Instead, remove the "View Cart" button and change the code so that clicking one of the "Add to Cart" buttons directly updates the "cart_area" division.

Part 2: Understanding Code Separation - JavaScript that generates JavaScript

  1. Each "Add to Cart" button is redundant because it includes the name of the product which is already a list item in the HTML document. Imagine if we had hundreds of items. Manually coding each button creates opportunity for many error and inconsistencies.
  2. Instead, start with this file shop2.html and generate the buttons automatically.
  3. Note that this file contains copious comments to help you complete this part.
  4. Important: JavaScript is a great way to dynamically add elements to an HTML document rather than manually inserting them inline. Amazingly, we are actually using JavaScript to generate the proper JavaScript function call. Web programming often involves writing code (JavaScript and PHP) that outputs JavaScript and PHP. It is crazy!
  5. Show your instructor that your shop2.html is properly working to get credit for the in-lab.

Connecting to web server via FTP

To test PHP code, you must always do three things:

  1. Save your file locally.
  2. Upload your file to the web server.
  3. Test your PHP on the server. By typing the URL (for example http://lastname.sienacs.com/script.php) or by refreshing the page if it is already load. If you do not see your changes, do a hard refresh (hold SHIFT key and press the refresh/reload button on the web browser).
The instructions above will ensure that your newly saved code is being properly run on the server., i.e., an HTTP request is made to the server. Depending the cache settings and how you navigate to a back a web page, some web browsers (mostly IE and older versions of Safari) will fetch the cached (i.e., locally stored) web page and you will NOT be executing your newly saved code on the server.

  • Hostname: ftp.sienasellbacks.com
  • Username: lastname@sienasellbacks.com
  • Password: Told to you in lab3
  • Settings: Use FTP, not SFTP and SCP which are not supported
  • Server URL: lastname.sienacs.com

Part 3: PHP Shopping Cart

Important: In parts 1 and 2, the items in the shopping cart are actually stored in a JavaScript array. This array will be completely re-initialized if the web page is reloaded in the web browser. In part 4, we will use sessions to store the information more permanently.

But first, we will implement the shopping cart with PHP to better understand the difference between client-side (JavaScript) and server-side (PHP) processing. Similar to JavaScript, when an HTTP request is made, the PHP is script is completely re-executed on the server. All declared variables including the cart array are re-initialize and all the previously stored data is lost. Again, in part 4, we will use session which can persistently store data across HTTP requests..

  1. Save shop3.txt to your lab folder.
  2. Rename shop3.txt to shop3.php
  3. Open shop3.php in Notepad++ and examine the two hyperlinks for Spam and Mountain Dew
  4. Using the two examples as a model, add appropriate hyperlinks for the other items (Beef Jerky, iPad Air, etc.).
  5. Note that hyperlinks are another way to pass information to the server. In this case, we are passing a variable called "item" whose value is the name of the item we want to add to the cart.
  6. Examine the PHP function called print_cart and change the code so that it prints an ordered list instead of an unordered list.
  7. Inside the cart_area div, add the following PHP code:
    <div id="cart_area">
    <?php print_cart($cart) ?>
    </div>
    
  8. Note that a PHP tag <?php ?> can be inserted anywhere inside an HTML document. The PHP code inside the tag is executed and the output of the code (echo or print) is inserted in place of the PHP tag. Isn't this awesome?!
  9. Save shop3.php and be sure to upload it to the server in a folder called lab5
  10. Test the script on the server at http://lastname.sienacs.com/lab5/shop3.php
  11. Note that this script does not work properly because each time we click a hyperlink, the browser makes an HTTP request, and the PHP script is completely re-executed which re-initializes the $cart array.

Part 4: PHP Shopping Cart with Sessions

  1. A PHP-enabled web server can create a super-global variable called $_SESSION which will allow you to save information on the server. Unlike a global variable, which gets re-initialized each time the script is executed, the super-global $_SESSION will preserve its values across HTTP requests. Thus, you can modify a variable and it will be "remembered" the next time the script is executed.
  2. In shop3.php replace the top line of PHP code ($cart = array();) with the following code:
    session_start();
    if ($_SESSION['cart'] == null) {
      $_SESSION['cart'] = array();
    }
    if ($_GET['clear'] == true) {
      session_unset();
      session_destroy();
    }
    
  3. Modify the array_push so that it uses the session variable instead of $cart:
    array_push($_SESSION['cart'], $newItem);
    
  4. Modify the print function call in the "cart_area" so it also uses the session:
    <?php print_cart($_SESSION['cart']) ?>
    
  5. Add the following hyperlink near the "cart_area" so we can clear the session completely:
    <a href="shop3.php?clear=true">Clear Cart</a>
    
  6. Save your file.
  7. Upload it to the server in your lab5 folder.
  8. Test the script at http://www.sienacs.com/lab5/shop3.php
  9. Show your instructor you working script to get full credit of the in-lab activity

Part 5: Understanding Sessions

Read the following information because it is really important. It is actually the basis for how all modern web applications track individual users. But also, this information is needed for you to complete the last part of the lab. Finally, you will be tested on some of these concepts on the next exam, so read it thoroughly.

  • The function session_start() is very powerful.
  • Keep in mind that a PHP script (shop3.php for example) is always initiated by an HTTP request, i.e., your web browser requests that http://www.sienacs.com/lab5/shop3.php be executed on the server.
  • The first time session_start() is executed by a particular web browser request, the function performs three important operations:
    1. It generates a unique session_id and stores it on the server in a session space. On a busy web server, there can be millions of active sessions stored in the session space which is why busy servers need a lot of RAM
    2. It initializes a super global variable called $_SESSION that can be used by the calling script (shop3.php for example) to store information.
    3. It immediately sends back an HTTP response to the web browser and requests that the session_id be saved as a cookie called PHPSESSID on the web browser. Thus, a script (shop3.php for example) cannot output any information prior to executing session_start() because printing or echoing output actually triggers the HTTP response. For everything to work, session_start() needs to be the first output-generating line of code in your script.
  • If the web browser allows cookies to be save (most do), the session_id will be saved locally and will be associated with the primary domain of the website (www.sienacs.com for example).
  • Task: See how your web browser stores the session_id generated by http://www.sienacs.com/lab5/shop3.php:
    1. Click the Chrome menu on the browser toolbar. .
    2. Select Settings
    3. Click Show advanced settings
    4. In the "Privacy" section, click the Content settings...
    5. In the "Cookies" section, click All cookies and site data
    6. Search for www.sienacs.com
    7. Click on the PHPSESSID cookie to see all the meta information about this cookie.
  • When a cookie is set for a particular URL domain (www.sienacs.com for example), the cookie is sent in all subsequent HTTP requests to the particular domain. In other words, all the cookies (names and values) are actually sent back to the server when any new HTTP requests are made.
  • When the server receives an HTTP request with a PHPSESSID cookie, it will use the stored session_id to lookup and restore the $_SESSION array for the script.
  • Read more about sessions here: Damn Good Session Tutorial with Code examples

Part 6: Simple Login

Using what you learned in the last two labs and from reading the Damn Good Session Tutorial with Code examples, create a single script called login.php and be sure to upload it to your lab5 folder, so that it is accessible at http://lastname.sienacs.com/lab5/login.php.

Use login.txt to get started.

Your script should do the following:

  • Your script should have a password field
  • If the password equal "abc123" you should welcome the user and set $_SESSION['authorized'] = true;
  • Then, if $_SESSION['authorized'] equals true you script should print the welcome message and not the login form.
  • Your script should have a logout link that goes to the URL: login.php?logout=true
  • At the top of your script right after you start the session, you should see if $_GET['logout'] equals true and if so you should completely unset and destroy the session:
    				session_unset();
    				session_destroy();
    
  • Thus, if you refresh the page you should once again see the login form because the $_SESSION['authorized'] variable was destroyed, i.e., it is now null and not true.

Deliverables

  1. Submit your working insert.php program to Blackboard.