~~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)
';
?>
* URL encode user input, then convert results into valid HTML (e.g. & -> &)
';
?>
===== 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]] )
----
Popcorn Sales - for PHP handling
===== Example – Popcorn Sales Receipt =====
* //The results page -- HTML with embedded PHP//: popcorn3.php
----
Process the popcorn3.html form
Customer:
$street
$city
");
?>
Order Information
Product |
Unit Price |
Quantity Ordered |
Item Cost |
Unpopped Popcorn |
$3.00 |
|
|
Caramel Popcorn |
$3.50 |
|
|
Caramel Nut Popcorn |
$4.50 |
|
|
Toffey Nut Popcorn |
$5.00 |
|
|
");
printf("Your total bill is: $ %5.2f
",$total_price);
print("Your chosen method of payment is: $payment
");
?>
* Output
Customer:
Order Information
Product |
Unit Price |
Quantity Ordered |
Item Cost |
Unpopped Popcorn |
$3.00 |
0 |
$ 0.00 |
Caramel Popcorn |
$3.50 |
0 |
$ 0.00 |
Caramel Nut Popcorn |
$4.50 |
0 |
$ 0.00 |
Toffey Nut Popcorn |
$5.00 |
0 |
$ 0.00 |
You ordered 0 popcorn items
Your total bill is: $ 0.00
Your chosen method of payment is:
===== 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|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 =====
$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'' for ''eof''; ''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''((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:
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
----
//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.
===== 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:
:
");
$_SESSION['page_number']++;
?>
===== 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]]