Table of Contents

~~SLIDESHOW~~

PHP for Web Applications

Supplementary Material

Provided for Reference. This material is no longer taught on this module.

Lecturer: Dr Chris P. Jobling.

Using PHP for web applications development.

PHP for Web Applications

We conclude our review of the Basics of PHP with a discussion of its use in creating web applications.


Based on Chapter 12 of Robert W. Sebasta, Programming the World-Wide Web, 3rd Edition, Addison Wesley, 2006. and Chapter 12 of Chris Bates, Web Programming: Building Internet Applications, 3rd Edition, John Wiley, 2006.

Contents of this Lecture

PHP for web applications with examples

The Examples for PHP for Web Applications.

Learning Outcomes

At the end of this lecture you should be able to answer these questions:

  1. How can the value of a form element be accessed by a PHP script?
  2. What is a file variable?
  3. What is a file pointer?
  4. What does an fopen function return if it fails?
  5. Explain the parameters and actions of the fread function.

Learning Outcomes (continued)

At the end of this lecture you should be able to answer these questions:

  1. What is returned by the fwrite function?
  2. How can a cookie be created in a PHP script?
  3. How can a script determine whether a particular cookie exists?
  4. How can a variable be saved in a session?

Queries and Query Strings

   GET /webapp.cgi?query_string HTTP/1.1
   Host: some.host.com
    :
   POST /webapp.cgi HTTP/1.1
   Host: some.host.com 
    :
   
   query_string

Processing GET rquests

A Real GET request

GET /cgi-bin/echo_params.cgi?colour=light&taste=malty HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-GB; rv:1.8.1.9) Gecko/20071025 Firefox/2.0.0.9 Creative ZENcast v2.00.14
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://localhost/beer_get.html

Processing POST requests

A Real POST request

POST /cgi-bin/echo_params.cgi HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-GB; rv:1.8.1.9) Gecko/20071025 Firefox/2.0.0.9 Creative ZENcast v2.00.14
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://localhost/beer_post.html
Content-Type: application/x-www-form-urlencoded
Content-Length: 24

colour=light&taste=malty

Query String Format

    name=value
    milk=2&payment=visa

URL Specification

“…Only alphanumerics [0-9a-zA-Z], the special characters ”$-_.+!*'(),“ , and reserved characters used for their reserved purposes may be used unencoded within a URL.”

URL Encoding


For more more information on URL encoding see 1)

URL Encoding – Examples

  <?php
    echo '<a href="mycgi?foo=', urlencode($userinput), '">';
  ?>
  <?php
    $query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
    echo '<a href="mycgi?' . htmlentities($query_string) . '">';
  ?> 

PHP and Query Data

Query parameters

Form Handling

Example – Popcorn Sales

<html>

  <form action = "popcorn3.php"
  method = "post">
    <h2> Welcome to Millennium Gymnastics Booster Club Popcorn
    Sales </h2>
    <table>
      <!-- Text widgets for the customer's name and address -->
      <tr>
        <td> Buyer's Name: </td>
        <td>
        <input type = "text" name = "name"
        size = "30" required placeholder="Your name"/>
        </td>
      </tr>
      <tr>
        <td> Street Address: </td>
        <td>
        <input type = "text" name = "street"
        size = "30" required placeholder = "Street"/>
        </td>
      </tr>
      <tr>
        <td> City, State, Zip: </td>
        <td>
        <input type = "text" name = "city"
        size = "30" required placeholder="City, State, Zip"/>
        </td>
      </tr>
    </table>
    <p />
    <table border = "border">
      <!-- First, the column headings -->
      <tr>
        <th> Product </th>
        <th> Price </th>
        <th> Quantity </th>
      </tr>
      <!-- Now, the table data entries -->
      <tr>
        <td> Unpopped Popcorn (1 lb.) </td>
        <td> $3.00 </td>
        <td align = "center">
        <input type = "number" name = "unpop"
        size = "3" min="0" pattern="\d+" />
        </td>
      </tr>
      <tr>
        <td> Caramel Popcorn (2 lb. canister) </td>
        <td> $3.50 </td>
        <td align = "center">
        <input type = "number" name = "caramel"
        size = "3" min="0" pattern="\d+" />
        </td>
      </tr>
      <tr>
        <td> Caramel Nut Popcorn (2 lb. canister) </td>
        <td> $4.50 </td>
        <td align = "center">
        <input type = "number" name = "caramelnut"
        size = "3" min="0" pattern="\d+" />
        </td>
      </tr>
      <tr>
        <td> Toffey Nut Popcorn (2 lb. canister) </td>
        <td> $5.00 </td>
        <td align = "center">
        <input type = "number" name = "toffeynut"
        size = "3" min="0" pattern="\d" />
        </td>
      </tr>
    </table>
    <p />
    <!-- The radio buttons for the payment method -->
    <h3> Payment Method </h3>
    <p>
      <input type = "radio" name = "payment" value = "visa"
      checked = "checked" />
      Visa
      <br />
      <input type = "radio" name = "payment" value = "mc" />
      Master Card
      <br />
      <input type = "radio" name = "payment"
      value = "discover" />
      Discover
      <br />
      <input type = "radio" name = "payment" value = "check" />
      Check
      <br />
      <br />
      <!-- The submit and reset buttons -->
      <input type = "submit" value = "Submit Order" />
      <input type = "reset" value = "Clear Order Form" />
    </p>
  </form>

</html>


<!DOCTYPE html>
<!-- popcorn3.html - This describes the popcorn sales form -->
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title> Popcorn Sales - for PHP handling </title>
  </head>
  <body>
    <form action = "popcorn3.php"
    method = "post">
      <h2> Welcome to Millennium Gymnastics Booster Club Popcorn
      Sales </h2>
      <table>
        <!-- Text widgets for the customer's name and address -->
        <tr>
          <td> Buyer's Name: </td>
          <td>
          <input type = "text" name = "name"
          size = "30" required placeholder="Your name"/>
          </td>
        </tr>
        <tr>
          <td> Street Address: </td>
          <td>
          <input type = "text" name = "street"
          size = "30" required placeholder = "Street"/>
          </td>
        </tr>
        <tr>
          <td> City, State, Zip: </td>
          <td>
          <input type = "text" name = "city"
          size = "30" required placeholder="City, State, Zip"/>
          </td>
        </tr>
      </table>
      <p />
      <table border = "border">
        <!-- First, the column headings -->
        <tr>
          <th> Product </th>
          <th> Price </th>
          <th> Quantity </th>
        </tr>
        <!-- Now, the table data entries -->
        <tr>
          <td> Unpopped Popcorn (1 lb.) </td>
          <td> $3.00 </td>
          <td align = "center">
          <input type = "number" name = "unpop"
          size = "3" min="0" pattern="\d+" />
          </td>
        </tr>
        <tr>
          <td> Caramel Popcorn (2 lb. canister) </td>
          <td> $3.50 </td>
          <td align = "center">
          <input type = "number" name = "caramel"
          size = "3" min="0" pattern="\d+" />
          </td>
        </tr>
        <tr>
          <td> Caramel Nut Popcorn (2 lb. canister) </td>
          <td> $4.50 </td>
          <td align = "center">
          <input type = "number" name = "caramelnut"
          size = "3" min="0" pattern="\d+" />
          </td>
        </tr>
        <tr>
          <td> Toffey Nut Popcorn (2 lb. canister) </td>
          <td> $5.00 </td>
          <td align = "center">
          <input type = "number" name = "toffeynut"
          size = "3" min="0" pattern="\d" />
          </td>
        </tr>
      </table>
      <p />
      <!-- The radio buttons for the payment method -->
      <h3> Payment Method </h3>
      <p>
        <input type = "radio" name = "payment" value = "visa"
        checked = "checked" />
        Visa
        <br />
        <input type = "radio" name = "payment" value = "mc" />
        Master Card
        <br />
        <input type = "radio" name = "payment"
        value = "discover" />
        Discover
        <br />
        <input type = "radio" name = "payment" value = "check" />
        Check
        <br />
        <br />
        <!-- The submit and reset buttons -->
        <input type = "submit" value = "Submit Order" />
        <input type = "reset" value = "Clear Order Form" />
      </p>
    </form>
  </body>
</html>

Example – Popcorn Sales Receipt


<!DOCTYPE html>
<!-- popcorn3.php - Processes the form described in
popcorn3.html
-->
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title> Process the popcorn3.html form </title>
  </head>
  <body>
    <?php
// Get form data values
$unpop=$_POST["unpop"];
$caramel=$_POST["caramel"];
$caramelnut=$_POST["caramelnut"];
$toffeynut=$_POST["toffeynut"];
$name=$_POST["name"];
$street=$_POST["street"];
$city=$_POST["city"];
$payment=$_POST["payment"];
// If any of the quantities are blank, set them to zero
if($unpop=="")
$unpop=0;
if($caramel=="")
$caramel=0;
if($caramelnut=="")
$caramelnut=0;
if($toffeynut=="")
$toffeynut=0;
// Compute the item costs and total cost
$unpop_cost=3.0*$unpop;
$caramel_cost=3.5*$caramel;
$caramelnut_cost=4.5*$caramelnut;
$toffeynut_cost=5.0*$toffeynut;
$total_price=$unpop_cost+$caramel_cost+$caramelnut_cost+$toffeynut_cost;
$total_items=$unpop+$caramel+$caramelnut+$toffeynut;
// Return the results to the browser in a table
    ?>
    <h4> Customer: </h4>
    <?php
print("$name <br /> $street <br /> $city <br />");
    ?>
    <p />
    <p />
    <table border = "border">
      <caption>
        Order Information
      </caption>
      <tr>
        <th> Product </th>
        <th> Unit Price </th>
        <th> Quantity Ordered </th>
        <th> Item Cost </th>
      </tr>
      <tr align = "center">
        <td> Unpopped Popcorn </td>
        <td> $3.00 </td>
        <td><?php print("$unpop");?></td>
        <td><?php printf("$ %4.2f",$unpop_cost);?></td>
      </tr>
      <tr align = "center">
        <td> Caramel Popcorn </td>
        <td> $3.50 </td>
        <td><?php print("$caramel");?></td>
        <td><?php printf("$ %4.2f",$caramel_cost);?></td>
      </tr>
      <tr align = "center">
        <td> Caramel Nut Popcorn </td>
        <td> $4.50 </td>
        <td><?php print("$caramelnut");?></td>
        <td><?php printf("$ %4.2f",$caramelnut_cost);?></td>
      </tr>
      <tr align = "center">
        <td> Toffey Nut Popcorn </td>
        <td> $5.00 </td>
        <td><?php print("$toffeynut");?></td>
        <td><?php printf("$ %4.2f",$toffeynut_cost);?></td>
      </tr>
    </table>
    <p />
    <p />
    <?php
print("You ordered $total_items popcorn items <br />");
printf("Your total bill is: $ %5.2f <br />",$total_price);
print("Your chosen method of payment is: $payment <br />");
    ?>
  </body>
</html>

<html>

      <h4> Customer: </h4>
   <br />  <br />  <br />    <p /> <p />

<table border = “border”>

    <caption> Order Information </caption>
    <tr>
      <th> Product </th>
      <th> Unit Price </th>
      <th> Quantity Ordered </th>
      <th> Item Cost </th>
    </tr>
    <tr align = "center">
      <td> Unpopped Popcorn </td>
      <td> $3.00 </td>
      <td> 0 </td>
      <td> $ 0.00        </td>
    </tr>
    <tr align = "center">
      <td> Caramel Popcorn </td>
      <td> $3.50 </td>
      <td> 0 </td>
      <td> $ 0.00        </td>
      </tr>
    <tr align = "center">
      <td> Caramel Nut Popcorn </td>
      <td> $4.50 </td>
      <td> 0 </td>
      <td> $ 0.00        </td>
    </tr>
    <tr align = "center">
      <td> Toffey Nut Popcorn </td>
      <td> $5.00 </td>
      <td> 0 </td>
      <td> $ 0.00        </td>
    </tr>
  </table>
  <p /> <p />
  You ordered 0 popcorn items <br />Your total bill is: $  0.00 <br />Your chosen method of payment is:  <br />

</html>

Files

Opening a File

  $fptr = fopen(filename, use_indicator)

File use indicators

Indicator Purpose
r read only, from the beginning
r+ read and write, from the beginning
w write only, from the beginning (also creates the file, if necessary)
w+ read and write, from the beginning (also creates the file, if necessary)
a write only, at the end, if it exists (creates the file, if necessary)
a+ read and write, read at the beginning, write at the end

File opening and closing

  $file_var = fopen("testdata.dat", "r") or
    die ("Error - testdata.dat cannot be opened");

File use cases

Read all or part of the file into a string variable

  $str = fread(file_var, number_of_bytes)

Read the lines of the file into an array

  $file_lines = file(file_name)

Read one line from the file

  $line = fgets(file_var, number_of_bytes)

Read one character at a time

  $ch = fgetc(file_var)
  while( ! feof($file_var) ) {
    $ch = fgetc($file_var);
  }

Writing to files

  $bytes_written = fwrite(file_var, string)

Storing Information about Client State

Session Tracking with Cookies

Baking Cookies

  setcookie(cookie_name, cookie_value, lifetime)
  setcookie("voted", "true", time() + 86400);

<note> Lifetime is measured in seconds. The value 86400 is 24 hours. The PHP function time() returns the number of seconds since the “UNIX epoch date” [Midnight GMT, 1st January 1970]. Thus the use of time() + 86400 creates a cookie that expires 24 hours from the time it was set. </note>

Consuming Cookies

Session Tracking

Session Tracking

Session Tracking: Example

  <?php session_start(); // must be called before any HTML is output 
  ?>
  :
  <?php
     if (!IsSet($_SESSION['page_number']))
        $_SESSION['page_number'] = 1;
     print("You have now visited " . $_SESSION['page_number'] . " pages <br />");
     $_SESSION['page_number']++;
  ?>

Summary of this Lecture

PHP for web applications with examples

The Examples for PHP for Web Applications.

Learning Outcomes

At the end of this lecture you should be able to answer these questions:

  1. How can the value of a form element be accessed by a PHP script?
  2. What is a file variable?
  3. What is a file pointer?
  4. What does an fopen function return if it fails?
  5. Explain the parameters and actions of the fread function.

Learning Outcomes (continued)

At the end of this lecture you should be able to answer these questions:

  1. What is returned by the fwrite function?
  2. How can a cookie be created in a PHP script?
  3. How can a script determine whether a particular cookie exists?
  4. How can a variable be saved in a session?

Homework Exercise

Write, test, and debug (if necessary) a PHP script for the following function. Write functions and the code to test them.

  1. Parameter: A file variable of a file of text, where the words are separated by spaces or colons. Return value: The word that appears most often in the file.

There are more exercises here and in the second coursework.

What's Next?

Database Access through the Web

Previous Lecture | home | Next Lecture

1)
Brian Wilson, URL Encoding (or: 'What are the “%20” codes in URLs?'), Index DOT Html, URL: http://www.blooberry.com/indexdot/html/topics/urlencoding.htm
2)
PHP Manual Page: Flock