Lab 6

Lab 6

PHP Basics

Working with forms, sessions, files and AJAX


Part 1: Welcome Script

Setup

  1. Click on the following PHP script, experiment with it, and notice it has a flaw
    welcome.php View PHP Code
  2. The script asks for your name and displays a welcome message. Then, the script asks for your favorite color and it is supposed to change the welcome message to your chosen color, but your name disappears. This is because the server can only remember your very last submission. In order to fix this problem, we must use sessions.
  3. In Notepad++, create a new file called welcome.php and save it in your lab6 folder.
  4. Copy and paste the PHP code of the welcome script above into your file.
  5. Save welcome.php to your lab6 folder.
  6. Using the connection setting that were emailed to you, upload your entire lab6 folder to the remote server and then disconnect from the server.
  7. Open the script in Chrome using the URL http://yourid.sienasellbacks.com/lab6/welcome.php where yourid is the username you were emailed.
  8. Make sure the script is working on the server

Fix It

  1. In Notepad++, edit the script to fix the flaw by using SESSION variables.
  2. Start a session by calling the session_start() function.
  3. Important: session_start() is typically the first line of code inside the first set of PHP tags.
  4. Then, we can copy the submitted form values to PHP SESSION variables as follows: $_SESSION['username'] = $_GET['username'];
  5. b>Important: You only want to copy the username if the user just submitted it. If $_GET['username'] is null, you do not want to set the session variable.
  6. Instead of using the GET variables to print the welcome message, we can use the SESSION variables as follows: Welcome '.$_SESSION['username'].'

Test on the server:

  1. Save welcome.php
  2. Upload your lab6 folder to the server. Disconnect from the server.
  3. Reload http://yourid.sienasellbacks.com/lab6/welcome.php in Chrome

Extend It

  1. Open welcome.php in Notepad++
  2. First, extend the script so that you can also add the font-size of the welcome message as follows:
    welcome_solution.php
  3. Hints:
    • When the user clicks "Add Color" change the submit button value to "Add Size" and the input text field's name to "size"
    • Add another else if clause to handle when the user clicks "Add Size"
    • Add more inline CSS to the welcome message: echo '<h2 style="font-size: '.$_SESSION['size'].'px;
  4. Second, improve the application so that it logs the users input in a text file called welcomedata.txt
  5. After printing/echoing the welcome message with the username, color and font-size, we can construct a comma-separate data string as follows:
    $datastring = $_SESSION['username'].",".$_SESSION['color'].",".$_SESSION['size']."\n";
    
  6. Then we can append this string to a file on the server as follows:
    $filename = "welcomedata.txt";
    $myfile = fopen($filename, "a");
    fwrite($myfile, $datastring);
    fclose($myfile);	  
    

Test on the server:

  1. Save welcome.php
  2. Upload your lab6 folder to the server. Disconnect from the server.
  3. Reload http://yourid.sienasellbacks.com/lab6/welcome.php in Chrome

Big Picture

The welcome.php script shows a typical PHP application that generates or modifies a series of forms. It also illustrates how PHP can dynamically change a web page's content and style based on submitted user information.

PHP Pros

PHP can receive form data easily using the $_GET variable and your application code remains hidden making it difficult for others to "steal" your core algorithms. PHP can store information temporarily via SESSIONS and permanently via files and databases.

PHP Cons

Updating a page requires a full HTTP request/response cycle where an entire page has to be transmitted, loaded and rendered. In fact, the extended welcome.php application requires 4 HTTP request/response cycles (one to load the initial form and one for each of the three entered values).

Generating web pages with PHP can lead to an unstructured mix of hard-coded HTML/CSS and dynamically-generated HTML/CSS.

Better Approach

Rather than generate and control the form with PHP, we can implement the form and all the behavior using the following JavaScript application:
welcome.html

This JavaScript mini-application will send the submitted data using AJAX to the following server-side script:
add_welcome_data.php

This script writes to the same file as the PHP script.

  1. Click on welcome.html and examine the source code. Notice how it uses a similar if-else-if statement to control the form elements to gather the username, color and font-size. Sadly, if you refresh the page, everything is lost. However, we only need one full HTTP request/response to load the page and one AJAX request to transmit the data.
  2. Notice how we transmit the data by "stringifing" a JavaScript object into a JSON-encoded string.
  3. Click on add_welcome_data.php to see the PHP code that appends to the file. Notice how we can parse the JSON-encoded string to create a PHP object.
  4. Note that in Part 2, you can use this as a model for completing the last part.

Part 2: Mad Libs

Setup

  1. Click on the following PHP script, experiment with it
    madlibs.php View PHP Code
  2. The script takes the user input and inserts it into one of two silly sentences. This script is annoying because each time you press a button the page reloads, the input disappears and you have to retype it.
  3. In Notepad++, create a new file called madlibs.php and save it in your lab6 folder.
  4. Copy and paste the PHP code of the mad libs script above into your file.
  5. Save your copy of madlibs.php to your lab6 folder.
  6. Using the connection setting that were emailed to you, upload your entire lab6 folder to the remote server and then disconnect from the server.
  7. Open the script in Chrome using the URL http://yourid.sienasellbacks.com/lab6/madlibs.php where yourid is the username you were emailed.
  8. Make sure the script is working on the server

Fix It

  1. In Notepad++, edit the script by using the POST method and by using SESSION variables to remember the posted data.
  2. Change the form method from "get" to "post"
  3. Throughout the PHP code, use the $_POST variable instead of the $_GET variable.
  4. Add a block of PHP code at the top of the file to start a session and save the posted form data to $_SESSION variables:
    <?php 
    session_start();
    $_SESSION['name'] = $_POST['name'];
    $_SESSION['verb'] = $_POST['verb'];
    ?>
    
  5. When generating the form, use the session variable to give each input element the previously stored value:
    <input type="text" name="name" value="<? echo $_SESSION['name'] ?>">
    
  6. Note that this illustrate one of the most complex syntax issues you will ever see as a Computer Scientist. We are embedding a PHP echo statement inside of the quotes of an HTML attribute value. PHP cannot access the document objects because the document is not rendered on the server. The only way to put values into attributes is to literally print/echo the value inside of hard-coded HTML.
  7. Instead of setting the local PHP variables based on the $_GET or $_POST variable, which might have been forgotten, use the values stored in the session variables: $name = $_SESSION['name'];

Test on the server:

  1. Save madlibs.php
  2. Upload your lab6 folder to the server.
  3. Reload http://yourid.sienasellbacks.com/lab6/madlibs.php in Chrome

Extend It

  1. In Notepad++, extend madlibs.php so that you can enter six word and can select three different sentences:
    welcome_solution.php
  2. This script also logs the users input in a text file called welcomedata.txt
  3. Add another additional form elements and session variables for six different words
  4. Add an additional sentence button and else if to generate a third sentence from the six words.
  5. In addition to printing/echoing the sentence, store the sentence as a string called $sentence and append it to a file as follows:
    $filename = "sentencedata.txt";
    $myfile = fopen($filename, "a");
    fwrite($myfile, $sentence);
    fclose($myfile);	  
    

Test on the server:

  1. Save madlibs.php
  2. Upload your lab6 folder to the server.
  3. Reload http://yourid.sienasellbacks.com/lab6/madlibs.php in Chrome

Implement the Better Approach

Rather than generate and control the form with PHP, we can implement the form and all the behavior using JavaScript.

Using the JavaScript Welcome application as a model (see below), implement the Mad Libs application using JavaScript and AJAX:
welcome.html

Your file should be called madlibs.html. Use the welcome.html application as a model.

This JavaScript mini-application will send the submitted sentences using AJAX to a server-side script:
add_sentence_data.php

  • In Notepad++, create a new file called add_sentence_data.php and save it in your lab6 folder.
  • Copy and paste the PHP code of the add_sentence_data.php into your file.
  • This script writes to the same file as the extended PHP application.

    Unlike the Welcome application which sent an object with three fields, this application sends a single string. Thus, you do not have to use JSON to stringify the data object.

    DELIVERABLE

    Create a zip file of your lab6 folder called lab6.zip and submit the file in Blackboard.

    In the comment area of Blackboard put your partner's name.

    Not finished?

    The deliverable must be submitted in Blackboard by midnight on the day before your next scheduled lab meeting. If you wish to work alone, you can submit the deliverable yourself. However, you are encouraged to work with your partner and you can submit together. When submitting as a lab pair, be sure to include your partner's name in the comment area when you submit via Blackboard.

    Do not share

    Outside of lab, you are only permitted to work with your lab partner. Do not share your work with any other student.