User Tools

Site Tools


eg-259:lecture18

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
eg-259:lecture18 [2008/12/01 08:20] eechriseg-259:lecture18 [2013/03/08 18:04] (current) – [PHP for Web Applications] eechris
Line 1: Line 1:
 +~~SLIDESHOW~~
 +====== PHP for Web Applications ======
  
 +**Supplementary Material**
 +
 +Provided for Reference. This material is no longer taught on this module.
 +
 +**Lecturer**: [[C.P.Jobling@Swansea.ac.uk|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//
 +
 +    * [[eg-259:lecture18#queries_and_query_strings|Queries and Query Strings]]
 +    * [[eg-259:lecture18#form_handling|Form Handling]]
 +    * [[eg-259:lecture18#files|Files]]
 +    * [[eg-259:lecture18#storing_information_about_client_state|Storing Information about Client State]]
 +    * [[eg-259:lecture18#session_tracking|Session Tracking]]
 +
 +The [[eg-259:examples:php1#example_from_lecture_18|Examples for PHP for Web Applications]].
 +
 +
 +===== Learning Outcomes ====
 +
 +
 +//At the end of this lecture you should be able to answer these questions//:
 +
 +   - How can the value of a form element be accessed by a PHP script?
 +   - What is a file variable?
 +   - What is a file pointer?
 +   - What does an ''fopen'' function return if it fails?
 +   - 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//:
 +
 +   - What is returned by the ''fwrite'' function?
 +   - How can a cookie be created in a PHP script?
 +   - How can a script determine whether a particular cookie exists?
 +   - How can a variable be saved in a session?
 +
 +
 +
 +
 +
 +===== Queries and Query Strings =====
 +
 +  * Parameters sent to a Web Application from a web browser take the form of a //query string//
 +  * The //query string// is either appended to the URI in a GET request as in:
 +
 +     GET /webapp.cgi?query_string HTTP/1.1
 +     Host: some.host.com
 +      :
 +
 +  * or is carried in the payload of a POST request as in:
 +
 +     POST /webapp.cgi HTTP/1.1
 +     Host: some.host.com 
 +      :
 +     
 +     query_string
 +
 +
 +===== Processing GET rquests =====
 +
 +  * Web server passes two environment variables to helper application
 +  * ''$REQUEST_METHOD=GET'' and ''$QUERY_STRING=query_string'' 
 +  * The query string will be content of ''$QUERY_STRING'' (everything in resource name after query marker ''?'')
 +
 +
 +===== A Real GET request =====
 +
 +  * //From [[http://localhost/beer_get.html|beer example]]// 
 +
 +  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
 +
 +----
 +
 +  * Web application is ''/cgi-bin/echo_params.cgi''
 +  * Host is ''localhost''
 +  * Query string is ''colour=light&taste=malty''
 +  * Although data comes from a form (//referer// is http://localhost/beer_get.html), request is equivalent to and indistinguishable from URI: http://localhost/cgi-bin/echo_params.cgi?colour=light&taste=malty.
 +
 +
 +
 +===== Processing POST requests =====
 +
 +  * Data passed to helper application in //environment variables// and //standard input//
 +  * ''$REQUEST_METHOD=POST''
 +  * ''$CONTENT_LENGTH'' gives size of payload
 +  * ''$CONTENT_TYPE'' is type of data: usually ''application/x-www-form-urlencoded''
 +  * Query string is ''$CONTENT_LENGTH'' bytes read from //standard input//
 +
 +
 +
 +===== A Real POST request =====
 +
 +  * //Also from [[http://localhost/beer_post.html|beer example]]// 
 +
 +  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
 +
 +----
 +
 +  * Web application is ''/cgi-bin/echo_params.cgi''
 +  * ''Host'' is ''localhost''
 +  * ''Content-Type'' is ''application/x-www-form-urlencoded''
 +  * ''Content-Length'' is 24 bytes
 +  * Query string is ''colour=light&taste=malty'' (is ASCII 24 bytes in length)
 +
 +
 +===== Query String Format =====
 +
 +
 +    * A query string includes names and values of HTML form elements (widgets)
 +    * Widget values are always coded as strings
 +    * The form of a name/value pair in a query string is:
 +
 +      name=value
 +
 +    * If the form has more than one widget, their values are separated with ampersands:
 +
 +      milk=2&payment=visa
 +
 +
 +
 +
 +===== URL Specification =====
 +
 +  * The specification for URLs ([[http://www.rfc-editor.org/rfc/rfc1738.txt|RFC 1738]], Dec. '94) limits the use of allowed characters in URLs to only a limited subset of the US-ASCII character set:
 +
 +> "...Only alphanumerics ''[0-9a-zA-Z]'', the special characters "''$-_.+!*'(),''" , and reserved characters used for their reserved purposes may be used unencoded within a URL."
 +
 +  * Any source of general text that appears in an HTML page that may be represented in a URL has to be encoded to ensure that illegal characters do not appear.
 +  * This includes widget names, and widget values.
 +
 +
 +
 +
 +
 +===== URL Encoding =====
 +
 +    * Performed automatically by Browser on form submission
 +    * Each special character is encoded as a percent sign and a two-character hexadecimal number (the ASCII code for the character)
 +    * Some browsers code spaces as plus signs, rather than as ''%20''
 +    * You should URL encode any text that will be sent to the browser in a form widget, or in the ''action'', ''src'', ''href'', etc.
 +
 +----
 +
 +For more more information on URL encoding see ((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))
 +
 +
 +===== URL Encoding – Examples =====
 +
 +  * URL encode general text (e.g. from file input or results of a previous form submission)
 +<code php>
 +  <?php
 +    echo '<a href="mycgi?foo=', urlencode($userinput), '">';
 +  ?>
 +</code> 
 +  * URL encode user input, then convert results into valid HTML (e.g. & -> &amp;)
 +<code php>
 +  <?php
 +    $query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
 +    echo '<a href="mycgi?' . htmlentities($query_string) . '">';
 +  ?> 
 +</code>
 +
 +
 +===== PHP and Query Data =====
 +
 +    * PHP takes care of extracting the query parameters for you
 +    * It maps the HTTP request fields into PHP variables
 +    * It extracts the query string from the HTTP request, extracts the name/value pairs and places them into an array.
 +    * Array ''$_GET'' will contain data for GET method and ''$_POST'' will contain data passed by the POST method
 +       * value subscripts are the widget names
 +    * This is transparent and it does not matter whether GET or POST method is used to transmit the form data
 +          
 +
 +
 +===== Query parameters =====
 +
 +
 +    * If the query string has ''colour=light&taste=malty''
 +    * ''$_POST["colour"]'' will return ''"light"'' and ''$_POST["taste"]'' will return ''"malty"'' 
 +    * Query matching will also turn check box group ''colour=red&colour=blue'' to an array so that ''$_POST["colour"]'' returns the right thing. 
 +
 +
 +===== Form Handling =====
 +
 +
 +    * Simple in PHP
 +    * Forms could be handled by the same document that creates the form, but that may be confusing
 +    * Better to separate "view" from data handling
 +
 +
 +===== Example – Popcorn Sales =====
 +
 +   * //The Form Page (just HTML)// : [[/~eechris/eg-259/examples/lecture18/popcorn3.html|popcorn3.html]] ( [[http://localhost/eg-259/examples/lecture18/popcorn3.html|popcorn3.html @ localhost]] )
 +
 +<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>
 +
 +----
 +
 +<code 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>
 +</code>
 +
 +
 +
 +===== Example – Popcorn Sales Receipt =====
 +
 +
 +    * //The results page -- HTML with embedded PHP//: popcorn3.php
 +
 +----
 +<code php>
 +<!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>
 +</code>
 +
 +  * Output
 +
 +<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 =====
 +
 +
 +    * PHP can:
 +          * Deal with any files on the server
 +          * Deal with any files on the Internet, using either HTTP or FTP
 +    * Instead of filehandles, PHP associates a variable with a file, called the //file variable// (for program reference)
 +    * A file has a //file pointer// (where to read or write)
 +
 +
 +===== Opening a File =====
 +
 +
 +    * Command to open a file and assign to a file variable:
 +<code php>
 +  $fptr = fopen(filename, use_indicator)
 +</code>
 +
 +===== 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 =====
 +
 +   * Because //fopen// could fail, use it with die:
 +<code php>
 +  $file_var = fopen("testdata.dat", "r") or
 +    die ("Error - testdata.dat cannot be opened");
 +</code>
 +    * Use ''file_exists(filename)'' to determine whether file exists before trying to open it
 +    * Use ''fclose(file_var)'' to close a file
 +
 +
 +
 +
 +===== File use cases =====
 +
 +  - [[#read_all_or_part_of_the_file_into_a_string_variable|Read all or part of the file into a string variable]]
 +  - [[#read_the_lines_of_the_file_into_an_array|Read the lines of the file into an array]]
 +  - [[#read_one_line_from_the_file|Read one line from the file]]
 +  - [[#read_one_character_at_a_time|Read one character at a time]]
 +
 +
 +
 +===== Read all or part of the file into a string variable =====
 +
 +<code php>
 +  $str = fread(file_var, number_of_bytes)
 +</code>
 +  * To read the whole file, use ''filesize(file_name)'' as the second parameter
 +
 +
 +
 +
 +===== Read the lines of the file into an array =====
 +
 +<code php>
 +  $file_lines = file(file_name)
 +</code>
 +  * Need not open or close the file
 +
 +
 +===== Read one line from the file =====
 +
 +<code php>
 +  $line = fgets(file_var, number_of_bytes)
 +</code>
 +   * Reads characters until //eoln//, //eof//, or ''number_of_bytes'' characters have been read
 +
 +
 +
 +
 +===== Read one character at a time =====
 +
 +<code php>
 +  $ch = fgetc(file_var)
 +</code>
 +  * Control reading lines or characters with //eof// detection using ''feof'' (''TRUE'' for ''eof''; ''FALSE'' otherwise):
 +<code php>
 +  while( ! feof($file_var) ) {
 +    $ch = fgetc($file_var);
 +  }
 +</code>
 +
 +
 +===== Writing to files =====
 +
 +
 +    * To write to a file use:
 +<code php>
 +  $bytes_written = fwrite(file_var, string)
 +</code>
 +    * ''fwrite'' returns the number of bytes it wrote
 +    * Files can be locked (to avoid interference from concurrent accesses) with ''flock''((PHP Manual Page: [[http://uk3.php.net/flock|Flock]]))
 +
 +
 +
 +
 +===== Storing Information about Client State =====
 +
 +    * A session is the time span during which a browser interacts with a particular server
 +    * The HTTP protocol is stateless
 +    * But, there are several reasons why it is useful for the server to relate a request to a session
 +          * Shopping carts for many different simultaneous customers
 +          * Customer profiling for advertising
 +          * Customized interfaces for specific clients
 +    * Approaches to storing client information:
 +          * Store it on the server -- often too much to store!
 +          * Store it on the client machine -- this works
 +
 +===== Session Tracking with Cookies =====
 +
 +
 +    * A cookie is a small object of information consisting of a name and a textual value
 +    * Cookies are created by some software system on the server
 +    * Every HTTP communication between the browser and the server includes information in its header about the message
 +    * At the time a cookie is created, it is given a lifetime
 +    * Every time the browser sends a request to the server that created the cookie, while the cookie is still alive, the cookie is included
 +    * A browser can be set to reject all cookies
 +
 +
 +
 +===== Baking Cookies =====
 +
 +    * Create a cookie with setcookie:
 +<code php>
 +  setcookie(cookie_name, cookie_value, lifetime)
 +</code>
 +    * e.g.:
 +<code php>
 +  setcookie("voted", "true", time() + 86400);
 +</code>
 +    * Cookies must be created before any other HTML is created by the script
 +
 +
 +----
 +
 +<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 =====
 +
 +    * Cookies are obtained in a script the same way form values are obtained, using the ''$_COOKIES'' array
 +
 +===== Session Tracking =====
 +
 +
 +    * For session tracking, PHP creates and maintains a session tracking id
 +    * Create the id with a call to ''session_start'' with no parameters
 +    * Subsequent calls to ''session_start'' retrieves any session variables that were previously registered in the session
 +
 +===== Session Tracking =====
 +
 +
 +    * To create a session variable, use the global array ''$_SESSION''
 +
 +===== Session Tracking: Example =====
 +
 +
 +    * To count number of pages visited in a web site, put the following code in all documents:
 +<code php>
 +  <?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']++;
 +  ?>
 +</code>
 +
 +
 +===== Summary of this Lecture =====
 +
 +//PHP for web applications with examples//
 +
 +    * [[eg-259:lecture18#queries_and_query_strings|Queries and Query Strings]]
 +    * [[eg-259:lecture18#form_handling|Form Handling]]
 +    * [[eg-259:lecture18#files|Files]]
 +    * [[eg-259:lecture18#storing_information_about_client_state|Storing Information about Client State]]
 +    * [[eg-259:lecture18#session_tracking|Session Tracking]]
 +
 +
 +The [[eg-259:examples:php1#examples_from_lecture_18|Examples for PHP for Web Applications]].
 +
 +
 +
 +===== Learning Outcomes ====
 +
 +
 +//At the end of this lecture you should be able to answer these questions//:
 +
 +   - How can the value of a form element be accessed by a PHP script?
 +   - What is a file variable?
 +   - What is a file pointer?
 +   - What does an ''fopen'' function return if it fails?
 +   - 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//:
 +
 +   - What is returned by the ''fwrite'' function?
 +   - How can a cookie be created in a PHP script?
 +   - How can a script determine whether a particular cookie exists?
 +   - 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.
 +
 +  - //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 [[eg-259:homework:18|here]] and in the [[eg-259:cw2|second coursework]].
 +
 +
 +
 +===== What's Next? =====
 +
 +**Database Access through the Web**
 +
 +  * [[eg-259:lecture19#relational_databases|Relational Databases]] 
 +  * [[eg-259:extras:dbandsql|Introduction to SQL]] (not examined)
 +  * [[eg-259:lecture19#architectures_for_database_access|Architectures for Database Access]]
 +  * [[eg-259:lecture19#the_mysql_database_system|Introducing MySQL]] 
 +  * [[eg-259:lecture19#database_access_with_php_mysql|Database Access with PHP and MySQL]] 
 +
 +
 +
 +[[eg-259:lecture17|Previous Lecture]] | [[eg-259:home]] | [[eg-259:lecture19|Next Lecture]]