WDD Tutorial 10 - Introduction to PHP

advertisement
Introduction to Web Development
Introduction to PHP
Table of Contents
Introduction to PHP Tutorial ............................................................................................................ 2
Introduction to PHP ...................................................................................................................... 2
Conventions .............................................................................................................................. 2
What you need for this tutorial ................................................................................................. 2
PHP: Working with Strings .............................................................................................................. 3
Creating a Simple Example .......................................................................................................... 3
Explaining the Simple Example ................................................................................................... 3
Exercise 1 – String Handling ....................................................................................................... 4
Exercise 2 – More Strings ............................................................................................................ 4
PHP and XHTML............................................................................................................................. 5
Creating a Web Form ................................................................................................................... 5
HTML Input Controls – Web Forms............................................................................................ 5
Form Element ........................................................................................................................... 6
Input element ............................................................................................................................ 6
Text Area Element ................................................................................................................... 7
Select Element .......................................................................................................................... 7
PHP, XHTML and Web Standards .............................................................................................. 8
Exercise 3 – Construct a Web Form............................................................................................. 8
Handling Form Posts .................................................................................................................... 9
Exercise 4 – Handling Form Post ................................................................................................. 9
Embedding PHP ......................................................................................................................... 10
Exercise 5 – XHTML Form Handling ....................................................................................... 10
Further Exercises ............................................................................................................................ 11
© Trevor Adams, Staffordshire University
-1-
Introduction to Web Development
Introduction to PHP
Introduction to PHP Tutorial
Introduction to PHP
This tutorial will introduce you to the basic features of server-side technology used for web
design and development. It is assumed that you are comfortable with XHTML and CSS topics
introduced earlier in the module and the exercises will require you to be familiar with the
operations related to such topics, such as creating a web form. Any XHTML elements introduced
for the first time will be explained in this document. By the end of this tutorial, you will have
produced a server-side form handling script for confirming user data entered via an XHTML
form.
Conventions
This type of print indicates an exercise. They are usually present at the end of a major
section of information
This type of text indicates a code example / listing. You may wish
to type this code out or copy & paste.
Italic text indicates code elements inline with a sentence e.g.
the <h1> element.
What you need for this tutorial

Access to the tutor's web site

A suitable web page / CSS / PHP editor such as Microsoft® Notepad® or Microsoft
Expression Web or Adobe Dreamweaver.

An understanding of the topics presented in the previous tutorials. Please ensure that you
are comfortable and grasp the concepts from all prior XHTML & CSS tutorials before
proceeding.

Access to the Introduction to PHP lecture notes, language syntax and features
© Trevor Adams, Staffordshire University
-2-
Introduction to Web Development
Introduction to PHP
PHP: Working with Strings
Working with text is a staple task of any programmer at any level. Working with text is
particularly relevant with web programming as all data over HTTP has to be passed as text. Any
conversion to other types of data, such as a number has to be done at the server side via parsing.
You shall begin by looking at a few examples while building up your familiarity with how PHP
works within XHTML.
Creating a Simple Example
Create a new folder to store the files you create as part of the tutorial walkthroughs and exercises.
This folder will need to reside on local web server space or a web site which allows you to
execute PHP scripts.
Create a new text file, using Microsoft® Notepad, placing the code listing (Figure 1) below into
it. Save this file as helloworld.php. Ensure that you specify the extension as .php or this example
will not function correctly – in fact all PHP files require the .php extension.
<?php
$person = "John Doe";
$msg = "Hello, World!";
echo "$person says $msg";
?>
Figure 1 String example code
In order to view your file you have to access the PHP file via a local web server or on the intranet
e.g. - http://localhost/helloworld.php.
Explaining the Simple Example
The code created should produce the message John Doe says Hello, World! As you can see, the
variables initialised before the echo statement are expanded in-place when using the echo
statement. This is a useful feature of PHP which not many languages offer, usually requiring a
series of concatenations (adding strings together) to achieve the same result. There are a number
of things you can change to alter this behaviour, which is not always desirable.
© Trevor Adams, Staffordshire University
-3-
Introduction to Web Development
Introduction to PHP
Save helloworld.php as helloworld2.php and alter the code so it matches the code listing below
(Figure 2). The only real change is the in the echo statement line. Open your PHP file and
examine the results.
<?php
$person = "John Doe";
$msg = "Hello, World!";
echo '$person says $msg';
?>
Figure 2 Single quote version - helloworld02.php
Exercise 1 – String Handling
Looking at the two files created, helloworld.php and helloworld2.php, can you explain the
difference between the outputs produced by each file. What is the significance of using a
double-quote in place of a single quote to demark a string? Referring to the lecture notes,
how might you output a dollar sign if using double-quotes?
Hint: The technique required is called character ‘escaping’.
Exercise 2 – More Strings
Create a file called helloworld3.php populated with the code listing given in Figure 3. Explain
the define statement and describe what the functions strlen(), strtoupper() and strtoupper() do
(you may wish to examine the output and/or the PHP manual for assistance). Can you
explain why the define statement was used and how it affects output? Would the define
statement be necessary if not viewing the output through a web browser?
<?php
define("BR", "<br />");
$person = "John Doe";
$msg = "Hello, World!";
$output = "$person says $msg";
$length = strlen($output);
echo "$output" . BR . "Output Length: $length Chars";
echo BR . "Upper case: " . strtoupper($output);
echo BR . "Lower case: " . strtolower($output);
?>
Figure 3 Exercise 2 code listing
© Trevor Adams, Staffordshire University
-4-
Introduction to Web Development
Introduction to PHP
PHP and XHTML
PHP is a highly useful tool for creating web applications. Many web sites today offer
personalisation features, e-mail listing and other customisable options which all require some
form of application programming. PHP is well suited for dynamic web page creation as it can be
embedded within XHTML mark-up. This section will introduce you to HTML forms, the main
method of interacting with a web site, and how to handle form input.
Creating a Web Form
The first step you shall undertake is the creation of an XHTML web form. This will be a simple
mock-up that represents a basic mailing list subscription form, a sample form viewed in a
browser might look like the screen shot in Figure 4.
Figure 4 Sample mailing list subscription form
HTML Input Controls – Web Forms
Web forms are created in XHTML mark-up using the form element (refer to the lecture notes).
Each form element can contain a number of input elements that, when rendered using a browser,
represent user interface controls that your web site users can interact with and input data.
Ordinarily, HTML has no way of handling form posts, PHP on the other hand is more than
capable of handling form posts.
© Trevor Adams, Staffordshire University
-5-
Introduction to Web Development
Introduction to PHP
Form Element
Contains four main attributes that are required for proper use with this tutorial:

name – provides the name attribute with a unique value on the page

id – set to the same as name for each form element

method – set to post for the exercises in this tutorial, could also be get

action – the name of the file that will handle the form post, which could, if needed, be the
same file that contains the form
The form element contains all other form input controls and represents a block-level element and
can be styled as such using CSS
<form name="frmName" id="frmName" method="post"
action="handleform.php">
Input element
The input element is more complicated than the form element and can represent a number of
different user interface controls depending on the values of the attributes it contains. All input
types must set the following attributes so they can be used with forms:

name – set to the name of the control variable

id – unique name set to the control on the page

value – value that the control has

type – type of control to render (some types have additional attributes which are available
in XHTML specifications and within Dreamweaver and Expression Web
The main types of input controls are:

text – renders as a text box in the browser, the value attribute represents the default text to
be displayed by the control; utilises a maxlength attribute that caps the number of
characters that may be entered into the text box control.

password – same as text input type but displays hidden text as * instead of actual
characters.

radio – renders as an option or radio button in the browser window. Use a radio button
when you wish to present a series of options where only one option may be chosen. A
group of option elements should be set the same name attribute and different id attributes.
© Trevor Adams, Staffordshire University
-6-
Introduction to Web Development
Introduction to PHP
The value that each option represents should be placed in the value attribute. Implements
a selected attribute which can be set to selected if the option button should be initialised
as chosen (good for defaults).

checkbox – renders as a check/tick box in the browser window. They operate similar to a
radio button except the id and name attributes should be identical per element. A check
box control represents a Boolean value and is not affected by other checkboxes in the
form. The value attribute represents the value passed to the form handler if the form is
posted with a check in the control box. The control implements a checked attribute, which
when set to selected, renders the control with a tick as default.

submit – renders the input control as a button which will invoke the file and post the
contents of the form that is specified in the form’s action attribute. The value attribute of
this element represents the text displayed on the button control.
Text Area Element
The text area element (textarea) represents a multi-line text box. It has an id, name and a
readonly attribute available. It is represented in mark-up as:
<textarea name="mytxt" id="mytxt">Text content</textarea>
Should you wish to make the contents of the text area read only, add the attribute
readonly="readonly".
Select Element
The select element represents a list box that may contain a number of options that a user may
pick from. It has the following standard attributes:

id – unique identifier in the mark-up

name – used as a name reference to the value posted
Each select element can contain one or more option elements that are used to represent the
options available within a given list. Each option element has a value (representing a potentially
different value than the display text) and a content that is used to render the option on screen. For
example:
<select name="names" id="names">
<option value="tja1">Trevor Adams</option>
<option value="flk1">Fiona Knight</option>
<option value="pcw1">Phil Windridge</option>
</select>
© Trevor Adams, Staffordshire University
-7-
Introduction to Web Development
Introduction to PHP
Renders as (although the value to be passed to the handling form would be given by the option
element’s value attribute):
Figure 5 rendered select element as shown in browser
The option element can host a selected attribute, which when given the value of selected, selects
the chosen option by default in the select element.
PHP, XHTML and Web Standards
PHP files can accommodate XHTML 1.0 Transitional easily without modification. This is due to
PHP using the name attribute for the input elements to access the posted values. The name
attribute is not valid in XHTML 1.0 Strict documents as it has been dropped in favour of the id
attribute as the only identifying attribute for an element. When using XHTML 1.0 Transitional
documents, the name and id attributes can happily co-exist. Use the id attribute to ensure
uniqueness within the mark-up and use the name attribute to reference the controls when using
PHP. Some input controls such as the radio type must have a group of objects having the same
name so they belong to the same group. Each radio control within a group should all have
different id attribute values to ensure validity and conformance to standards.
Exercise 3 – Construct a Web Form
Using your preferred web page editor (Dreamweaver or Microsoft Expression Web), create a
new file and save it as mailinglist.html. It should be XHTML 1.0 Transitional (not strict). And
contain the following elements (with associated attributes, case is important!):
- form element, name: frmRegister, method:post, action:handleform.php
- input element, type:text, name/id: txtName
- input element, type:text, name/id: txtEmail
- input element, type:radio name: optFormat, id:formatHTML, value:html
- input element, type:radio, name:optFormat, id:formatPlain, value:plain
- input element, type:submit, name:submit, value: Submit
Remember that all input elements should be contained within a form element. You may style
the HTML file with any CSS you wish. A sample of the form can be viewed in Figure 6.
Validate your document to ensure conformance to W3C standards.
© Trevor Adams, Staffordshire University
-8-
Introduction to Web Development
Introduction to PHP
Figure 6 Exercise 3 sample output
Handling Form Posts
Handling form posts with PHP is a very simple process. As explained in the accompanying
lecture to this tutorial, all values posted via form are available to a PHP script handling the form
in the $_POST array, indexed using the name attribute of the form element. For example, if a
form was posted containing an input element of type="text" and a name attribute of txtName,
PHP could access that value using:
<?php
echo $_POST["txtName"]; // case sensitive index
?>
All values by default arrive in the format of text. If a number type was required, use the variable
in the appropriate way and the variable will be converted for you by PHP.
Exercise 4 – Handling Form Post
Create a new PHP file in your folder called handleform.php. Place the code presented in
Figure 7 as its contents and save the changes. Test the XHTML web form created in
Exercise 3.
If you experience errors, ensure that the case of name attributes matches that of the values
given in this tutorial handout and you have transcribed them correctly to your PHP file
‘handleform.php’.
<?php
define("BR", "<br />");
$name = $_POST["txtName"];
$email = $_POST["txtEmail"];
$format = $_POST["optFormat"];
echo "Name: $name" . BR . "E-mail: $email" . BR ."Format: $format";
?>
Figure 7 Exercise 4 Code Listing
© Trevor Adams, Staffordshire University
-9-
Introduction to Web Development
Introduction to PHP
Figure 8 Sample output of exercise 4 as handleform.php
Embedding PHP
So far, the PHP scripts created as part of this tutorial have been fairly basic. They have generated
minimal output for the sake of gauging functionality. It is important to realise that PHP script can
be embedded anywhere (literally anywhere) in the .PHP file, just be enclosing the PHP script
within the <?php ?> tags. It is up to you, the developer, to ensure that your PHP script generates
valid XHTML. The only output the browser receives is mark-up generated after the PHP engine
has finished executing the code statements within. If you view the source of any of the PHP files
through a web browser you will not find any PHP code. It is time to make a more acceptable
form handler using XHTML to format and display the output results.
Exercise 5 – XHTML Form Handling
Design a XHTML document (transitional or strict) that will accept the form post and display
the results of the form. This could potentially be used as a method of asking for confirmation
in a real web site. Once you have designed an XHTML mock-up of your form handler, save
the file as handleform2.php and use PHP to embed the values of the form post. You should
use the file created in Exercise 4 as a guide.
A sample form handler that might be suitable is shown in Figure 9.
You may use any CSS rules that you see fit to make your form look presentable and
satisfactory to your needs. The illustration in Figure 9 is merely an example of what is
possible. You may wish t make the result of this exercise integrate with a site you may have
made in previous tutorials.
© Trevor Adams, Staffordshire University
- 10 -
Introduction to Web Development
Introduction to PHP
Figure 9 Sample form and handler using embedded PHP and XHTML
Further Exercises
If you complete all of the exercises in this tutorial, attempt the following additional exercise(s):

Construct a sample form to simulate registering a user for an e-commerce web site. Try to
use the most appropriate form elements for the task at hand. The form should be
compliant to XHTML 1.0 Transitional standard

Create a PHP/XHTML form handler for the registration form in the previous point. Have
the form output a confirmation of the information given.

Attempt to use the date function available to PHP to place the date/time of the form
(created in point 1) post in the confirmation form handler. Information regarding the date
function can be found at http://www.php.net/date.
© Trevor Adams, Staffordshire University
- 11 -
Download