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
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 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: usuallyapplication/x-www-form-urlencoded
- Query string is
$CONTENT_LENGTH
bytes read from standard input
A Real POST request
- Also from 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
islocalhost
Content-Type
isapplication/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 (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 1)
URL Encoding – Examples
- URL encode general text (e.g. from file input or results of a previous form submission)
<?php echo '<a href="mycgi?foo=', urlencode($userinput), '">'; ?>
- URL encode user input, then convert results into valid HTML (e.g. & → &)
<?php $query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar); echo '<a href="mycgi?' . htmlentities($query_string) . '">'; ?>
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) : 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>
<!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
- The results page – HTML with embedded PHP: popcorn3.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>
- 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:
$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
- Because fopen could fail, use it with die:
$file_var = fopen("testdata.dat", "r") or die ("Error - testdata.dat cannot be opened");
- 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
$str = fread(file_var, number_of_bytes)
- To read the whole file, use
filesize(file_name)
as the second parameter
Read the lines of the file into an array
$file_lines = file(file_name)
- Need not open or close the file
Read one line from the file
$line = fgets(file_var, number_of_bytes)
- Reads characters until eoln, eof, or
number_of_bytes
characters have been read
Read one character at a time
$ch = fgetc(file_var)
- Control reading lines or characters with eof detection using
feof
(TRUE
foreof
;FALSE
otherwise):
while( ! feof($file_var) ) { $ch = fgetc($file_var); }
Writing to files
- To write to a file use:
$bytes_written = fwrite(file_var, string)
fwrite
returns the number of bytes it wrote- Files can be locked (to avoid interference from concurrent accesses) with
flock
2)
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:
setcookie(cookie_name, cookie_value, lifetime)
- e.g.:
setcookie("voted", "true", time() + 86400);
- 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:
<?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
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 here and in the second coursework.
What's Next?
Database Access through the Web
- Introduction to SQL (not examined)