This document provides an introduction and overview of PHP 5. It covers setting up a development environment using XAMPP and NetBeans, and includes examples of basic PHP scripts. The document demonstrates how to output text from PHP code, use comments, and pass data between the server and browser. It also introduces PHP variables, forms, operators, and control structures. Later sections discuss object-oriented programming in PHP, MVC patterns, and interacting with MySQL databases.
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Php5
1. PHP 5
Prepared by : Dave Parkinson
Rick Ogden
www.webdesigninfo.co.uk
(September 2011)
2. PHP5 Page 2
PHP 5 CONTENTS
Chapter 1 : Introduction to PHP .............................................................................................. 4
1.1 Introduction to PHP ....................................................................................................................... 4
Chapter 2 : PHP ........................................................................................................................ 5
2.1 Your Development Environment ................................................................................................... 5
2.2 Your Development Tools ................................................................................................................ 8
2.3 Exercise 1 - Your First PHP Script (HelloWorld)...................................................................... 10
2.3.1 Analysis of your first PHP Script ............................................................................................................. 11
2.3.2 Sending Data to the Browser .................................................................................................................... 11
2.3.3 Comments in PHP code ............................................................................................................................ 12
2.4 Datatypes ....................................................................................................................................... 14
2.4.1 Scalar Datatypes ....................................................................................................................................... 14
2.4.2 Compound Datatypes .............................................................................................................................. 14
2.5 Variables ........................................................................................................................................ 15
2.5.1 Naming Variables ..................................................................................................................................... 16
2.5.2 Declaring Variables .................................................................................................................................. 16
2.5.3 Type Casting in PHP ................................................................................................................................ 18
2.5.4 Constants .................................................................................................................................................. 18
2.6 Communicating with the User ..................................................................................................... 19
2.6.1 Form Elements ......................................................................................................................................... 19
2.6.2 Submitting your Form .............................................................................................................................. 20
2.6.3 Gathering Information from a Form ......................................................................................................... 20
2.6.4 Exercise 2 (PassingData) .......................................................................................................................... 21
2.6.5 Gathering data from other Form Elements ............................................................................................... 22
2.7 Programming in PHP ................................................................................................................... 23
2.7.1 PHP Operators .......................................................................................................................................... 23
2.7.2 PHP Control Structures ............................................................................................................................ 25
2.7.3 PHP Functions .......................................................................................................................................... 26
2.8 Object Orientated Programming with PHP ............................................................................... 26
2.8.1 Classes and Objects .................................................................................................................................. 27
2.8.2 Using Object Orientation .......................................................................................................................... 28
2.8.3 Including a Class ...................................................................................................................................... 31
2.9 MVC ............................................................................................................................................... 32
2.9.1 Exercise 3 – A Template for a PHP Web Site using MVC ...................................................................... 33
2.10 Exercise 4 – A Simple Conversion Program ............................................................................. 37
2.11 Exercise 5 – A Simple Calculator .............................................................................................. 41
2.11.1 Using the Debugger in Net Beans .......................................................................................................... 42
2.11.2 var_dump Function ................................................................................................................................. 44
2.12 Maintaining Information on the Web ....................................................................................... 45
2.12.1 Using Cookies ........................................................................................................................................ 45
2.12.2 Using Session Variables ......................................................................................................................... 46
2.12.3 Exercise 6 – Writing and Reading Cookies & Session Variables .......................................................... 47
2.12.4 Query String ........................................................................................................................................... 51
2.12.5 Exercise 7 – Passing data between PHP pages ...................................................................................... 51
Chapter 3 : MySQL ................................................................................................................. 54
3.1 Introduction ................................................................................................................................... 54
Dave Parkinson
3. PHP5 Page 3
3.2 Creating a database using phpMyAdmin ................................................................................... 54
3.3 Using PHP with MySQL............................................................................................................... 57
3.3.1 Setting up and tearing down the connection ............................................................................................. 57
3.4 Interacting with the Database ...................................................................................................... 58
3.4.1 Structured Query Language ...................................................................................................................... 58
3.5 Exercise 8 - Reading data from a MySQL Database ................................................................ 61
3.6 Exercise 9 – Inserting, Updating and Deleting Records in a Database ................................... 67
3.7 Passing Data from a Database to a PHP Page ........................................................................... 71
3.7.1 Exercise 10 – Passing Information from a MySQL Database .................................................................. 71
3.8 Exercise 11 – Displaying Pictures from a MySQL Database ................................................... 72
Dave Parkinson
4. PHP5 Page 4
Chapter 1 : Introduction to PHP
1.1 Introduction to PHP
PHP originally stood for „Personal Home Page‟ when it was created in 1994 by Rasmus
Lerdorf. As its usefulness and capabilities grew it came to mean PHP:Hypertext
Preprocessor. According to the official web site www.php.net , PHP is „an HTML
embedded scripting language‟. In many ways it is very similar to Microsoft ASP scripting
language, and it offers virtually identical programming capability.
PHP is a widely-used general-purpose scripting language that is especially suited for Web
development and can be embedded into HTML. Since its inception PHP has seen an
exponential growth in its usage with PHP being deployed on over 20 million sites
worldwide. PHP is used on a similar number of sites to ASP.
PHP usually runs on a UNIX or LINUX operating system but a number of Windows web
hosting companies (e.g. Crystal Tech) offer PHP emulation on their Windows servers.
Dave Parkinson
5. PHP5 Page 5
Chapter 2 : PHP
2.1 Your Development Environment
PHP pages are simply text files on the web server. To create an PHP page all you really
need is a text editor such as Notepad.
However as you will need to add your PHP code to HTML code, debug the PHP code
locally on your PC, and upload your code to a web server then it makes sense to use an
Integrated Development Environment. In this module we will be using the Net Beans
IDE. In addition in order to run your code locally on your PC we will be using XAMPP
for Windows. XAMPP is an easy to install Apache Web Server distribution containing
MySQL, PHP and Perl. All these products are Open Source and free to install.
We will be setting up our development environment on a pen drive with 1 Mb of free
memory available (alternatively you could set up on the D: drive on the lab PC‟s -note the
environment is too large to fit on the F: drive).
In order to run PHP programs locally on our PC we need to install a web server. The best
options for this are either to install Microsoft‟s Information Server (IIS) or to install the
Apache Web Server (Open Source). Whichever web server we choice we also need to
install a PHP interpreter. Most PHP programmes need to access a database (usually
MySQL). It is often useful to install MySQL locally on your PC to enable you to fully test
your application without being connected to the web.
XAMPP is a free and open source cross-platform web server package, consisting mainly
of the Apache HTTP Server, MySQL database, and interpreters for scripts written in the
PHP and Perl programming languages. The program is released under the terms of the
GNU General Public License and acts as a free web server capable of serving dynamic
pages. XAMPP is available for Microsoft Windows, Linux, Solaris, and Mac OS X, and is
mainly used for web development projects. XAMPP requires only one zip or exe file to be
downloaded and run, and little or no configuration of the various components that make up
the web server is required. XAMPP is regularly updated to incorporate the latest releases
of Apache/MySQL/PHP and Perl.
One of the major advantages of XAMPP is that it allows you to install your development
environment onto a pen drive which can then be moved between different PC‟s enabling
you to work on your PHP project in any PC lab or on your home PC without changing
your configuration.
To install XAMPP on your pen drive go to http://www.apachefriends.org/en/xampp-
windows.html
Scroll down to the download section and select the installer version as shown below:
Dave Parkinson
6. PHP5 Page 6
Run the xampp-win32-1.7.4.exe file and when prompted select the path to install to point
to your pen drive (e.g. e:). This will install a number of files and directories under the
xampp directory on you pen drive as shown below:
Note that within the directory structure we have a directory called htdocs. Any files or
directories placed within htdocs will behave as if they have been uploaded onto an
external web server.
In order to test your development environment you need to run the file xampp-
control.exe found in your xampp directory.
Dave Parkinson
7. PHP5 Page 7
Start the services you require (for Web Server just start the Apache service). After Apache
starts, open the URL http://localhost/index.php and examine all of the XAMPP examples
and tools.
If you have problems starting the Apache service on your home PC there are several
possible problems.
Dave Parkinson
8. PHP5 Page 8
1. You are running Microsoft IIS web server locally on your machine (you must disable
this as only one web server can be used in your PC)
2. You are running a local version of MySQL (remove this as XAMPP adds its own
version of MySQL)
3. You are running some other program using the required ports (the usual problem will be
on Port 80). The likely candidate will be a peer-to-peer application. For example many
online TV services all use the Kontiki peer-to-peer network to share TV programmes. This
uses port 80 and will stop the Apache service working. In order to run Apache you need to
start Task Manager, go to Processes, then Show Processes from all Users, and end the
KService service. In order to restart this service and use your TV Player you will need to
restart your computer which will automatically restart the service.
2.2 Your Development Tools
In this module we will be using the NET Beans IDE to create our web projects. This
program has already been installed onto all our Computer suites. The following
information will show you how to install the development tools onto your home computer.
In order to run Net Beans we must first install the Java Development Kit. You can find
this at http://java.sun.com/javase/downloads/index.jsp
Choose the Java SE 7 Development Kit (JDK) as shown below and install it on your PC:
Dave Parkinson
9. PHP5 Page 9
Select Download JDK:
Select the correct Windows .exe file dependant on whether you have 32 bit or 64 bit
Windows, and install the JDK.
Once installed download the Net Beans IDE from:
http://www.netbeans.org/downloads/index.html
Choose the full version (ALL) as shown below and install the program on your PC:
Dave Parkinson
10. PHP5 Page 10
2.3 Exercise 1 - Your First PHP Script (HelloWorld)
Open Net Beans and open a New Project. Choose a PHP Category and a PHP Application.
Click Next and name your project helloworld (this will create your project in
E:xampphtdocshelloworld directory on your pen drive). Accept the defaults on the next
two screens then select Finish. This creates a file called index.php as shown below:
Add the following code to the body section of the file.
Dave Parkinson
11. PHP5 Page 11
<body>
<p>This page was created at <strong>
<?php
echo date(„l jS of F Y h:i:s A‟);
?>
</strong> on the computer running PHP.</p>
</body>
Save your file then test the file in your web browser by clicking on the run icon or by
going to the following URL:
http://localhost/helloworld/index.php
You should see the following :-
This page was created at Thursday 11th of August 2011 02:50:19 PM on the
computer running PHP.
Experiment with changing the parameters in the date function (look up the PHP date
format on the web).
2.3.1 Analysis of your first PHP Script
The script that we have produced is a mixture of HTML and PHP. Note that all the all the
PHP code is surrounded by a <?php and ?>. When an PHP page is requested from a web
server, the web server first fully processes all the code between <?php and ?> before
sending the output to the client.
The script consists of several lines of HTML and one line of PHP code. The line of PHP
code, displays the current date and time. The date function is built into PHP. The echo
command outputs the results of the date function to the client. Note that the browser just
receives HTML text from the web server, it does not receive any of the PHP code that was
between the <?php and ?> delimiters.
Each PHP statement must end with a semicolon.
2.3.2 Sending Data to the Browser
The echo command outputs information from the web server to the HTML seen in the web
browser.
You can use HTML formatting tags both inside and outside of your PHP code. For
example if we want to output the phrase Hello World in bold to a web page then we can
use either of the two options :-
Option 1 :
<strong>
<?php
echo „Hello World‟;
?>
</strong>
Dave Parkinson
12. PHP5 Page 12
Option 2 :
<?php
echo „<strong>Hello World</strong>‟;
?>
You can send multiple separate chunks of data to the Web browser using a dot.
<?php
echo „Hello World ‟ . „my name is Dave‟;
?>
2.3.3 Comments in PHP code
Documentation is very important in any application development. With Object Orientation
allowing multiple developers to work on the same application without the need to
understand the code that another developer has written, documentation is a way of
concisely explaining the information needed by the other developer without going into
detail as to what the code is doing.
Comments
In PHP there are 2 different ways of doing comments: line commenting and block
commenting. The single line comment is prefixed with a double slash (//). This can be on
a line of it's own, but normally it is placed after code:
<?php
echo 'Hello World!'; //prints the string 'Hello World!'
A comment block is depicted by starting with a slash then asterisk (/*) and ending with an
asterisk followed by a slash (*/). This is useful for commenting out blocks of code to
remove it from the application, and also for writing paragraphs of text. Normally when
writing a multi-lined comment, each line is prefixed with an asterisk.
<?php
/*
* My "Hello World!" script. This
* just prints out the string
* "Hello World!" to the console.
*/
echo 'Hello World!';
PhpDoc
PHP uses standard documentation syntax in order to allow automatic generation and use of
documentation. There are programs around that generate html documentation, and a lot of
IDEs (including NetBeans) will pick up on these comments, and give you hints when the
code that they reference are used. Normally a general description/comment is included
followed by some key words.
Key words are indicated with the @ symbol in front of them. The most common ones that
you will come across will be @param and @return. These are used above functions and
methods to explain what parameters it takes, and what is being returned. @param is
followed by the datatype, the parameter name and then an optional description.
Dave Parkinson
13. PHP5 Page 13
/**
* @param <type> $variableName A further description goes here
*/
The @return appears in much the same way but without the variable name:
/**
* @return <type> Description here
*/
If we were to put this above the profile class' constructor, this is what it would appear as.
/**
*The constructor takes the information of the person, and assigns
* them to properties.
*
* @param string $name Name of the person in the profile
* @param string $email The person's email address
* @param string $gender Whether they are male or female
* @param string $dob Their date of birth
*/
public function __construct($name, $email, $gender, $dob) {
$this->setName($name);
$this->email = $email;
$this->gender = $gender;
$this->dob = $dob;
}
And similarly, the getName() method:
/**
* Returns the name property from the object.
*
* @return string The person's name
*/
public function getName() {
return $this->name;
}
Further to these keywords, there are many more. Here are just a few, and these are
applicable mainly to class files:
@author The author of the class, normally in the form of: Person's Name <email address>
@copyright The copyright and ownership of the script/code/file
@license The release license of the code, normally in the form of: url License Name
@version The version of the file
@package The package which the file is a part of
Here is an example of the information for a class:
/**
* Profile is a class that contains the information of an individual
* profile which can be used to display a profile page, or part of a
* list of profiles on a page.
*
* @author Rick Ogden <r.l.ogden@salford.ac.uk>
* @copyright 2009 University of Salford
Dave Parkinson
14. PHP5 Page 14
* @license http://opensource.org/licenses/gpl-license.php GNU Public
License
* @version 1.0
* @package My Profile Site
*/
class Profile {
…
There are many more that can be found in the NetBeans PHP Docs.
2.4 Datatypes
A datatype is the generic name assigned to any data sharing a common set of
characteristics. Common datatypes include Boolean, integer, float, string and array.
2.4.1 Scalar Datatypes
Scalar datatypes are capable of containing a single item of information. Several datatypes
fall in this category including Boolean, integer, float and string.
Boolean
A Boolean variable may hold a value of either True or False.
Integer
An integer is a whole number (i.e. it has no decimal point). For example 4, 78 etc.
Float
Floating-point numbers may have a decimal point. For example 3.6, 6.7 etc.
String
A string can hold any sequence of letters, numbers, and symbols. Strings are distinguished
from code, variable names, and numbers by putting them between single or double
quotation marks. For example „My name is Dave‟, „hello‟, „28‟ are all strings. Note that
the string „28‟ is handled differently than the integer 28.
2.4.2 Compound Datatypes
Compound datatypes allow for multiple items of the same type to be aggregated under a
single representative entity. The array and the object fall into this category.
Array
It is often useful to aggregate a series of similar items together, arranging and referencing
then in some specific way. This data structure, known as an array, is formally defined as
an indexed collection of data values. Each member of the array index (also known as the
key) references a corresponding value and can be a simple numerical reference to the
values position in the series, or it could have some direct correlation to the value. For
Dave Parkinson
15. PHP5 Page 15
example, if we were to create a list of European countries, you could use a numerically
indexed array e.g.
$country[0] = „England‟
$country[1] = „France‟
$country[2] = „Germany‟
$country[3] = „Spain‟
However if the requirement was for a list of correlated capital cities to the countries then
we could use as associated indexed array e.g.
$capitals[„England‟] = „London‟
$ capitals [„France‟] = „Paris‟
$ capitals [„Germany‟] = „Berlin‟
$ capitals [„Spain‟] = „Madrid‟
Object
The other compound datatype supported by PHP is the object. PHP can use primitive
objects to hold data. These can be created, if needed, without initialisation. Many
languages (Java, JavaScript, C# etc..) use the dot notation to access properties (in the form
of object.property), whereas PHP uses the arrow notation from C++. This is a hyphen
followed by a closing angle-bracket ( -> ). This is used to both set and get properties from
within an object.
$myObject->myProperty = 'hello world!';
echo $myObject->myProperty; //prints "hello world!"
Property names can also be referenced by a variable containing a string. This is useful
when the property being requested may vary.
$myObject->myProperty = 'hello world!';
$myVar = 'myProperty';
echo $myObject->$myVar; // also prints "hello world!"
2.5 Variables
A variable is a small section of the computer‟s memory that you give a name to. In it you
can place numbers, letters, dates, sentences etc. The information that you put in a variable
can be accessed and manipulated by you.
There are many different types of data that may be stored in a variable. Some of the most
common are :-
integer
floating point
string
arrays
objects
Dave Parkinson
16. PHP5 Page 16
2.5.1 Naming Variables
The rules you must follow in naming variable are :-
A variable‟s name must start with a dollar sign ($) e.g. $name
The name can contain a combination of strings, numbers and the underscore e.g.
$my_report1
The first character after the dollar sign must be a letter or an underscore
Variable names are case sensitive. $name and $Name are different variables
Other suggestions to make your code easier to follow are :-
Include the variable type in the name. For example :-
$strName would be a string variable
$iNumber would be an integer variable
$dblNumber would be a floating point number
$bolName would be a Boolean variable (True or False)
This method of naming items is known as camel casing
Use descriptive names for variables
2.5.2 Declaring Variables
PHP is very casual in how it treats variables. You do not have to declare or initialise
variables, and you can convert from one variable type to another without problems.
To declare a string variable we use the following syntax :-
$firstname = „Dave‟;
$last_name = „Parkinson‟
$today = „January 1, 2004‟;
Enclosing a string within single quotes is useful when the string should be interpreted
exactly as stated. This means that any variables or escape sequences will not be interpreted
when the string is parsed.
To print out the value of a variable we do not use quotes e.g.
echo $firstname;
To print out the value of a string containing variables use echo with double quotation
marks e.g.
echo “Hello, $firstname”;
Another method of outputting a string containing a variable is to concatenate the variable
to the string using the period e.g.
Dave Parkinson
17. PHP5 Page 17
echo „Hello‟. $firstname;
You can concatenate strings using the period (.)
$name = $firstname . $last_name;
Heredoc syntax offers a convenient means of outputting large amounts of text. Rather than
delimiting strings with single or double quotes, two identical identifiers are employed e.g.
<?php
$mystring = <<<EOT
This is some PHP text.
It is completely free
I can use "double quotes"
and 'single quotes',
plus $variables too, which will
be properly converted to their values,
you can even type EOT, as long as it
is not alone on a line, like this:
EOT;
?>
There are several key things to note about heredoc, and the example above:
You can use anything you like; "EOT" is just an example
You need to use <<< before the delimiter to tell PHP you want to enter heredoc mode
Variable substitution is used in PHP, which means you do need to escape dollar
symbols - if you do not, PHP will attempt variable replacement.
You can use your delimiter anywhere in the text, but not in the first column of a new
line
At the end of the string, just type the delimiter with no spaces around it, followed by a
semi-colon to end the statement
Number variables (either integer or floating point) may be declared as follows :
$num1 = 83;
$num2 = 3.142;
$num3 = -45.6;
Unlike other languages, PHP does not require that you assign the size to an array at
creation time. PHP doesn‟t even require that you declare an array before using it, although
you are free to do so. You can create the array simply by making reference to it:
$country[0] = „England‟;
$country[1] = „France‟;
You can then display the first element of the array as follows
echo $country[0];
Dave Parkinson
18. PHP5 Page 18
Creating associative arrays is equally easy:
$country[„England‟] = „London‟;
$country[„France‟] = „Paris‟;
Alternatively you can use the array( ) construct to create an indexed array:
$country = array(„England‟, „France‟, „Germany‟, „Spain‟);
You can also use array( ) to create an associated array:
$capitals = array(„England‟ => „London‟,
„France‟ => „Paris‟,
„Germany‟ => „Berlin‟,
„Spain‟ => „Madrid‟);
2.5.3 Type Casting in PHP
Type casting in PHP works much as it does in other languages: the name of the desired
type is written in parentheses before the variable which is to be cast e.g.
$data = „10.5‟; //$data is a string
$num =(float) $data //$num is a floating point number
The casts allowed are:
(int), (integer) - cast to integer
(bool), (boolean) - cast to boolean
(float), (double), (real) - cast to float
(string) - cast to string
(array) - cast to array
(object) - cast to object
Note that tabs and spaces are allowed inside the parentheses.
Note: Instead of casting a variable to string, you can also enclose the variable in double
quotes.
$num = 10; // $num is an integer
$str = "$num"; // $str is a string
2.5.4 Constants
Constants are similar to variables in that you give it a name and store data in it. However
once declared the value of a constant cannot be changed. They are declared as follows :-
Define ( „VATRATE‟ , „0.0175‟);
Dave Parkinson
19. PHP5 Page 19
It is normal practice to use all capital letters for constants.
2.6 Communicating with the User
So far we have used PHP to send information to the browser. In order to make our PHP
web pages truly interactive we must also be able to obtain information from the user. In
order to obtain information from the user we must use forms. Forms contain text boxes,
list boxes, check boxes, radio buttons etc. to provide a variety of different ways of
collecting information from users of your web pages.
2.6.1 Form Elements
When you use a form you create a series of elements for your visitor to fill in. An example
of a form is given below :-
In order to get information from a form then you must first add a Form Control to your
page. You can then add a variety of different controls onto the form within your web page.
These include :-
Form : this is the form itself, all other form elements need to be placed within the form.
Text Field : this is where your visitor will input some text.
Button : can be either a submit or a reset button
Check Box : your visitor can select multiple check boxes if they wish.
Radio Button : unlike check boxes, when you click on a radio button you will uncheck all
the other radio buttons in the group (to belong to a group, radio buttons must have the
same name).
Dave Parkinson
20. PHP5 Page 20
List/Menu : either gives a popup list of entries (you can only select one of them) or a
menu list (you can select more than one option).
File Field : will allow your visitor to upload files to your web site.
Image Field : use this instead of a button to submit a form or perform an action.
Hidden Field : this icon represents a field that does not require any information to be
input from your visitor but that will still be processed by the PHP script.
Each of these controls must be given a unique name (and properties).
2.6.2 Submitting your Form
To gather the information from your form you need to add a submit button to it. When
your form is complete, this button will transmit the information contained within the form
to the PHP page you specify, where it can be processed.
Pressing the submit button will cause the button to be actioned with the attributes specified
for the form. What it will do is send the form to the Action address (this will be your PHP
page designed to process the form elements) set up as part of the form attributes. The form
Method must be set to POST.
A reset button is usually added to a form to allow the user to clear all the data from the
form elements and start again.
2.6.3 Gathering Information from a Form
Information from a form is gathered and processed in the PHP page that is specified in the
form‟s ACTION property.
To read the values of a form field, you need to use superglobal variables e.g. $_GET and
$_POST.
To demonstrate the use of $_POST superglobal variable, imagine that you have designed
a form with a text box on it to hold the name of the person accessing your web page. The
text field has been given the unique name firstname. The form then directs the user to a
PHP page that contains the following script :-
<html>
<body>
<?php
$name = $_POST[„firstname‟];
echo „Hello „ . $name;
?>
</body>
</html>
Dave Parkinson
21. PHP5 Page 21
If the person enters Dave in the form on the HTML page then the following information
will be output :-
Hello Dave
htmlentities
Whenever you allow your users to submit text to your website, you need to be careful that
you don't leave any security holes open for malicious users to exploit. If you are ever
going to allow user submitted text to be visible by the public you should consider using
the htmlentities function to prevent them from running html code and scripts that may be
harmful to your visitors.
The htmlentities function takes a string and returns the same string with HTML converted
into HTML entities. For example, the string "<script>" would be converted to
"<script>".
By converting the < and > into entities, it prevents the browser from using it as an HTML
element and it prevents the code from running if you were to display some user's input on
your website.
Anytime you allow users to submit content to your website, that other visitors can see, you
should consider removing the ability to let them use HTML. Although this will remove a
lot of cool things that your users can do, like making heavily customized content, it will
prevent your site from a lot of common attacks.
We can now change the above code as follows:
<html>
<body>
<?php
$name = htmlentities($_POST[„firstname‟]);
echo „Hello „ . $name;
?>
</body>
</html>
2.6.4 Exercise 2 (PassingData)
Open Net Beans and create a new PHP project called passingdata. Edit the index.php page
as shown below:
<body>
<div>
<p><strong>Please enter your name and birthday :-</strong></p>
<form name="form1" method="post" action="passingdata.php">
<div>
<label>Your name:</label>
<input type="text" name="name">
<br/>
<label>Your Birthday (in DD/MM/YY format):</label>
<input type="text" name="birthday">
Dave Parkinson
22. PHP5 Page 22
<br/>
<input type="submit" name="Submit" value="Submit">
<input type="reset" name="Submit2" value="Reset">
</div>
</form>
</div>
</body>
Note that if you just enter the text then press alt-shift-f the page will be automatically
formatted with the correct tab spacing.
This will create a web page containing two text boxes (note that we could have created
this as a HTML page as it contains no PHP code). The user is required to put his name in
the first text box (called name), and his date of birth in the second text box (called
birthday). A Submit button has been added to the page to process the form in an PHP
web page. A Reset button is also added to clear the form elements. Start the Apache web
server and open your web browser and view: localhost/passingdata. You should see the
following:
Add a new PHP Web Page (passingdata.php) to your project. This page will process the
data from the HTML form. The PHP page should output the name of the user and inform
him of his date of birth in the following manner :–
Hello Dave. You were born on 15/2/53
Add a link to this PHP page to allow you to return to your index.php page.
2.6.5 Gathering data from other Form Elements
There are times when a textbox is not a suitable method of gathering information. There
are times when you may wish to restrict the user to a specific set of choices. To do this
forms provide the capability of using list boxes, radio buttons and check boxes.
List Boxes :
List boxes allow the user to choice a response to a number of different options from a drop
down list box. When you add a list box to your form using Expression Web you can give
the list box a name and input a number of list values. For each item in the list box you can
add an item label (which will appear in your drop down list) and a value (which is what
will be returned when the data is requested using PHP). The value returned will
correspond to whatever item in the list box is selected by the user.
Dave Parkinson
23. PHP5 Page 23
Check Box :
Check boxes are used when you require a YES/NO response from the user. When you add
a check box to your form using Expression Web you can input a name for the check box
and a checked value which will only be returned if the user has checked the box.
Radio Buttons :
Radio buttons are similar to check boxes but unlike check boxes, when you click on a
radio button, you will uncheck all the other radio buttons in the group (to belong to a
group, radio buttons must have the same name). When you add a number of radio buttons
to your form using Expression Web you input the same name for each radio button in the
group. Each individual radio button, however, is given a different checked value which
will be returned to indicate which radio button has been selected.
2.7 Programming in PHP
PHP supports all the usual programming features. The syntax of PHP is virtually identical
to C++, C# and Java.
2.7.1 PHP Operators
Operators allow you to work with data. They allow you to combine, change and replace
data. There are several major classes of operator :-
Assignment Operator
The assignment operator is the equals sign (=). The assignment operator takes whatever is
on the right hand side of it and stores it in the left hand side of it e.g.
$Number = 3
$iNum = $iNum + 1
Arithmetic Operators
Example Name Result
$a + $b Addition Sum of $a and $b.
$a - $b Subtraction Difference of $a and $b.
$a * $b Multiplication Product of $a and $b.
$a / $b Division Quotient of $a and $b.
$a % $b Modulus Remainder of $a divided by $b.
The division operator ("/") returns a float value anytime, even if the two operands are
integers (or strings that get converted to integers).
Dave Parkinson
24. PHP5 Page 24
Comparison Operators
Example Name Result
$a = = $b Equal TRUE if $a is equal to $b.
$a != $b Not equal TRUE if $a is not equal to $b.
$a <> $b Not equal TRUE if $a is not equal to $b.
$a < $b Less than TRUE if $a is strictly less than $b.
$a > $b Greater than TRUE if $a is strictly greater than $b.
$a <= $b Less than or equal to TRUE if $a is less than or equal to $b.
$a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b.
Increment/decrement Operators
Example Name Effect
++$a Pre-increment Increments $a by one, then returns $a.
$a++ Post-increment Returns $a, then increments $a by one.
--$a Pre-decrement Decrements $a by one, then returns $a.
$a-- Post-decrement Returns $a, then decrements $a by one.
Logical Operators
Example Name Result
$a and $b And TRUE if both $a and $b are TRUE.
$a or $b Or TRUE if either $a or $b is TRUE.
$a xor $b Xor TRUE if either $a or $b is TRUE, but not both.
! $a Not TRUE if $a is not TRUE.
$a && $b And TRUE if both $a and $b are TRUE.
$a || $b Or TRUE if either $a or $b is TRUE.
String Operators
There are two string operators. The first is the concatenation operator ('.'), which returns
the concatenation of its right and left arguments. The second is the concatenating
assignment operator ('.='), which appends the argument on the right side to the argument
on the left side. For example
$a = „Hello „;
$b = $a . „World!‟; // now $b contains "Hello World!"
$a = „Hello ;
$a .= „World!‟; // now $a contains "Hello World!"
Dave Parkinson
25. PHP5 Page 25
2.7.2 PHP Control Structures
PHP supports all the commonly used control structures :-
if...elseif...else Statement
Use an if...elseif...else block to define several blocks of statements, one of which will
execute:
if (condition1)
code to be executed if condition is true;
elseif (condition2)
code to be executed if condition is true;
elseif (condition3)
code to be executed if condition is true;
else
code to be executed if condition is false;
switch Statement
The switch statement is a variant of the if-else combination. It is often used when you need
to compare a variable against a large number of variables.
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
code to be executed if n is different from both label1 and label2;
}
while Statement
The while loop executes a block of code while a condition is true.
while (condition)
{
code to be executed;
}
do-while Statement
The do...while statement will always execute the block of code once, it will then check the
condition, and repeat the loop while the condition is true.
do
{
code to be executed;
}
while (condition);
for Statement
The for loop executes a block of code a specific number of times
for (counter initialisation; loop test condition; loop modifier)
{
Dave Parkinson
26. PHP5 Page 26
sequence of statements;
}
statement after loop;
foreach Statement
The foreach statement is used for looping through arrays, pulling each key/value pair from
the array until all items have been retrieved or some internal condition has been met:
foreach ($array as $value)
{
code to be executed;
}
2.7.3 PHP Functions
PHP has more than 1000 functions already built into its standard distribution. You can
invoke a function simply by specifying the function name (for example the date function
we used in exercise1)
You can also write your own functions:
function functionName()
{
code to be executed;
}
To add more functionality to a function, we can add parameters. A parameter is just like a
variable. To let a function return a value, use the return statement. An example of a
function is shown below.
<?php
function add($x,$y)
{
$total= $x + $y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
When run this will output the following:
1 + 16 = 17
2.8 Object Orientated Programming with PHP
Object Orientation is a programming concept that was first developed in the 1960s, but did
not make its way into mainstream programming until the mid 1990s. It is a concept for
Dave Parkinson
27. PHP5 Page 27
writing efficient, organised and reusable code in applications, which as computing
hardware advances, are becoming increasingly larger and more complicated.
Although each programming language has its own implementation of Object Orientation,
the principles behind it remain similar across the board. Data is stored in instances of
classes (called objects), and objects have the ability to use and manipulate data contained
within it. Thus meaning that the code is completely self-sufficient.
This follows the same principles of keeping things organised and separate in order to
increase maintainability and structure.
2.8.1 Classes and Objects
Classes
Classes are containers of code that the programmer writes, and creates instances of (which
are called Objects). Think of the class as a blueprint for an object. Classes contain
properties (also known as class variables or fields), which are variables which can be used
throughout the class. Classes also contain methods (also known as functions), which can
use and modify the properties. Methods can also take arguments as parameters from code
outside the class, and return information, which can be used by other methods within the
object or external code.
Both methods and properties can be made visible or invisible to code outside the class,
thus increasing the security and integrity of the data within the class instance (object).
Generally a class looks like this:
<?php
class MyClass {
protected $var1 = '', $var2 = 0;
public function __construct() { //the constructor
//code goes here
}
public function methodOne() {
//more code
}
}
Objects
Objects are instances of classes. Each time you want to use a class, you create a new
instance of it. This means that you can have as many instances of classes as you like
without having to worry about conflicts. Your external code can then call methods and
fields (as long as they are public or “visible”).
$myObject = new MyClass(); //creates a new instance (object) of MyClass
$myObject->methodOne(); //performs the method "methodOne"
Examples
If we were to relate this to “real world” objects, we could say that a Dog was a class, and
instances of that class are created for each dog. The objects would contain information
Dave Parkinson
28. PHP5 Page 28
such as the dog's name, age, breed, colour etc.. and methods include things like make the
dog walk, bark, sit etc..
However, if we want to relate this to something more relevant to programming (and
particularly this module), you could take a website such as theregister.co.uk. The Register
is an IT news website. You could look at as having a News Item class, and each news item
is an object created from that class. The front page contains many instances of the News
Item class.
Green borders highlighting what could be objects of the class News item
This means that the same code for displaying news items on the front page can also be
used to display individual news items on the specific news item page, and also for the RSS
feed. In a normal website (with embedded code), you would need to repeat a lot of the
code.
2.8.2 Using Object Orientation
Creating a Class
As mentioned before, a class is a blueprint in which objects are constructed from. As an
example, we are going to build a profile of a person like you might get on a social
networking site, albeit a simple one. We need to create a class in order to instantiate
objects of people's profiles.
class Profile {
}
Notice how we start the class name with an upper-case letter? This is not required, but
good practice as it follows PHP standard conventions. Classes should start with upper-case
letters, but objects and methods should not.
We next need to decide the properties that the objects will hold. These are permanent
variables which are there throughout the existence of the object. Of course these properties
Dave Parkinson
29. PHP5 Page 29
will vary, but for simplicity we will just have the person's name, email, gender and date of
birth.
class Profile {
var $name = '', $email, $gender, $dob;
}
These properties (like standard PHP variables) can be initialised on creation, or left
uninitiated. Properties do not need to be declared at the top. However, it does help to keep
track of what properties an object has.
Constructor
When a new object is instantiated from a class, a specific method is run. This method is
called a Constructor. Although not required, nearly all classes have them, as they are used
to set up the object, and also provide information which can make that object differ from
another. Variables can be passed into the constructor using parameters.
In PHP the constructor method is always named “__construct” (that's a double underscore
in front of the word “construct”).
class Profile {
var $name = '', $email, $gender, $dob;
function __construct($name, $email, $gender, $dob) {
//constructor code here
}
}
This means that when you instantiate a new object, you need to pass four parameters into
the class.
$rick = new Profile('Rick
Ogden','r.l.ogden@salford.ac.uk','male','08/07/1986');
This is now passing information into the constructor, meaning that we can instantiate as
many objects from this class as we like, but passing different information in to make it
unique.
Self Referencing
In the previous example you will have noticed that we used the same names for the
parameters as we did for the properties. This will not cause a conflict as properties are
referenced to differently from local variables and parameters. If you want to retrieve a
property from an object, it's simply a case of referencing the object, and then the property
name.
$rick->name;
However, in order to for an object to refer to itself, you must use the predefined variable
$this.
class Profile {
var $name = '', $email, $gender, $dob;
Dave Parkinson
30. PHP5 Page 30
function __construct($name, $email, $gender, $dob) {
$this->name = $name;
$this->email = $email;
$this->gender = $gender;
$this->dob = $dob;
}
}
$rick = new Profile('Rick Ogden', 'r.l.ogden@salford.ac.uk', 'male',
'08/07/1986');
echo $rick->name; //prints 'Rick Ogden'
When a class uses the $this variable, it allows the object to refer to itself, complete with all
methods and properties. The $this variable can also be used as a return value (to return
itself) and also to send itself as a parameter to another object's method.
Encapsulation
Encapsulation is used in order to control which parts of our application are allowed to alter
what variables. Sometimes you may want variables to be specific values, and to validate
them before writing to the variable. Other variables you might not want any other parts of
application to get at. This is where visibility comes in. By default, in PHP everything is
public. However, visibility is controlled by the terms “public”, “private” and “protected”.
This can be placed before a method declaration, or replace the “var” declaration for a
property.
class Profile {
protected $name = '', $email, $gender, $dob;
public function __construct($name, $email, $gender, $dob) {
$this->name = $name;
$this->email = $email;
$this->gender = $gender;
$this->dob = $dob;
}
}
Public means that the property/method can be accessed/called from anywhere in the
application. Protected only allows the property/method to be accessed/called on from
within the class and subclasses, and private means it can't even be called or accessed from
within subclasses (this is rarely used for this reason, as it really limits expandability).
If we want to modify or retrieve a protected property, we use a mutator (setter) or accessor
(getter) method respectively. In these methods we can give external code “read” access to
the property, and validated write access.
Mutator methods take one or more argument, which determine what the property will be
changed to. Here is a very simple example of the mutator method “setName”. It checks to
make sure that the name is not empty.
public function setName($name) {
if(!empty($name)) { //makes sure it's not an empty string
$this->name = $name;
}
}
An accessor method can retrieve and if need be, format the property that is required. These
normally do not contain parameters, but may do if necessary for formatting.
Dave Parkinson
31. PHP5 Page 31
public function getName() {
return $this->name;
}
A method within a class can also call another method within the class. Instead of using the
object name like you do in your external code, you use the $this variable. So now our class
can look like this.
class Profile {
protected $name = '', $email, $gender, $dob;
public function __construct($name, $email, $gender, $dob) {
$this->setName($name);
$this->email = $email;
$this->gender = $gender;
$this->dob = $dob;
}
public function setName($name) {
if(!empty($name)) { //makes sure it's not an empty string
$this->name = $name;
}
}
public function getName() {
return $this->name;
}
}
This class can now be used as follows:
$rick = new Profile('Rick Ogden', 'r.l.ogden@salford.ac.uk', 'male',
'08/07/1986');
$rick->setName('Dave Parkinson');
echo $rick->getName(); //prints 'Dave Parkinson'
2.8.3 Including a Class
Once you have written your class, you need to include it into your web page. To keep your
code neat, each class should be in a separate file. This means that you then need to include
the classes where they're to be used.
Require Vs Include
People often get confused about where to use these two statements. The difference is that
if an included file cannot be found, the rest of the script will still run. Whereas with
require, the script will be terminated immediately. Generally it is recommended to
“require” a class, as there can be security issues with continuing to run a script if the
included class is not found.
As well as these, there are also include_once and require_once. These do exactly the same
as include and require, but mean that the included/required file will only be imported the
once, and if there are any further requests for that file, it will just ignore them.
Dave Parkinson
32. PHP5 Page 32
This is useful for importing our classes, as a class only needs to be included once.
Considering that over the development of an application, a class will probably be imported
into multiple directories, there is no point in importing it multiple times.
<?php
require_once('class.profile.php');
2.9 MVC
Until recently most PHP code was written by simply intertwining the PHP script with the
HTML text. Because the design of the web site is now inextricably linked with the
programming logic several problems arise, particularly when a large team are working on
the development of the web site:
Designers whose main task is to make the web site look good are now faced with the task
of learning PHP.
Developers who are later employed to expand the web site features are distracted by fixing
the bugs and security problems introduced by the novice. In the process of changing the
PHP script, they decide to add their own tweaks to the site design thus infuriating the
designers.
There is a solution that can go a long way to alleviating these issues, the MVC
architecture. Model–view–controller (MVC) is an architectural pattern used in software
engineering. Successful use of the pattern isolates business logic from the user interface,
permitting one to be freely modified without affecting the other. The controller collects
user input, the model manipulates application data, and the view presents results to the
user.
The model: The model defines the rules for the process an application is intended
to represent. You can think of it as the specification responsible for both the
applications data and its behaviour. For example if we were to write an application
that serves as a conversion calculator, allowing users to convert from miles to
kilometres, Fahrenheit to Celsius etc. The model is responsible for defining the
formulas used to perform such conversions, and when presented with a value and
desired conversion scenario, the model carries out the conversion and returns the
result. Note that the model is not responsible for formatting the data or presenting
it to the user. This is handled by the view.
The view: The view is responsible for formatting the data returned by the model
and presenting it to the user. It‟s possible for more than one view to utilise the
same model, depending on how the data should be presented.
The controller: The controller is responsible for determining how the application
should respond based on events occurring within the application space (typically
user actions), done by coordinating with both the model and the view to produce
the appropriate response.
Dave Parkinson
33. PHP5 Page 33
To better understand the dynamics of an MVC driven application consider the scenario
where we wish to develop an application involving the conversion application. The
following actions take place:
The user desires the application to perform an action, e.g. converting an input temperature
from Fahrenheit to Celsius. The user then submits the form by clicking a submit button.
The controller responds by identifying the appropriate action, gathering the input
from the form, and supplying it to the model.
The model executes the function responsible for converting Fahrenheit to Celsius
and returns the calculated and returns the calculated value to the controller.
The controller calls the appropriate view, passing along the calculated value. The
view renders and returns the result to the user.
2.9.1 Exercise 3 – A Template for a PHP Web Site using MVC
Download the file templates.zip from Blackboard and unzip it into your htdocs directory
under XAMPP. This template (written by Rick Ogden) uses the 960gs CSS framework to
design the site structure. In the Views/template directory it contains a header.phtml and a
footer.phtml which are included on every new page generated. To add additional pages
just edit the file header.phtml to add the extra link and then add a new controller
(pagex.php) and a new view (pagex.phtml) for each page required.
If you run the project you will view the following web site:
Dave Parkinson
34. PHP5 Page 34
The home page explains how use the template. It includes a link to the free, open source
CSS template, 960gs CSS Framework, which has been used to design the site. Click on
this link to find more information on the framework.
The template written for the MVC architecture contains the following files and directories.
Views Directory
This directory contains a subdirectory called template with two files, footer.phtml and
header.phtml. This files will be appended onto every page of your web site to maintain a
consistent look and feel to all your pages. You will need to edit the header.phtml file to
add a new link to the unordered list every time you add a new page to your site. It also
contains the file index.phml and page1.phtml which are the views for the two pages on
your website.
CSS Directory
The subdirectory css (within the main css directory) contains all the files for the 960gs
CSS Framework. It must not be edited.
The style.css file contains all the styles for your site.
Dave Parkinson
35. PHP5 Page 35
#title, #menu, #footer {
background-color: #00584a;
color: #fff;
}
#menu a {
color: #fff;
text-decoration: none;
background-color: #008a7f;
display: block;
padding: 3px;
}
#menu li {
list-style: none;
margin: 2px;
}
#menu {
height: 300px;
}
#footer {
text-align: center;
}
.datatable td {
border: 1px solid #000;
padding: 2px;
}
.label {
width: 100px;
}
.inputtd {
width: 400px;
}
.datatable th {
width: 100px;
}
.radbuttons, .inputtable {
width: 70%;
}
.standardwidth {
width: 200px !important;
}
You need to edit this file to add new styles and to change to look of your site.
Images Directory
Dave Parkinson
36. PHP5 Page 36
This directory is used to store all the images on your site. Currently it contains one image
used in the header.
Models Directory
Currently unpopulated but will be used to store all your models used on your website.
Index.php
<?php
$view = new stdClass();
$view->pageTitle = 'Homepage';
require_once('Views/index.phtml');
Sets the name of the page title and loads the view for the page. A similar file page1.php
performs the same operation for the second page in your website.
For all the remaining exercises on this PHP module we will be using this template to build
a multi page website to run the exercises. To start our website we will rename the project
with your surname e.g. parkinson. Right click on the templates project and select rename.
Rename the project yoursurname (also select Rename Project Folder).
Before we can run the project we need to change the include information. Right click on
the include section of the website and click properties. This will open a dialog box. Select
Run Configuration and change the Project URL to reflect the new name of your project.
Dave Parkinson
37. PHP5 Page 37
Run the site.
2.10 Exercise 4 – A Simple Conversion Program
We will be creating a simple PHP program to convert miles to kilometres and vice versa
using the MVC architecture.
We will add a new page to the website we created in the previous exercise. The new page
will be called converter.
The Models directory will contain the file responsible for the processing of data. We will
add a file called class.converter.php.
The Views directory will contain the file responsible for displaying the data (e.g. the
HTML). We will add a file called converter.phtml.
The controller (converter.php) is a file called when the visitor to the site clicks on the
converter link in the navigation section of the site. It handles the user‟s input, processes
the data using the model and displays the results using the view.
In order to create our website we will start with the Model (although we could equally
well start by writing the view).
Create a new PHP Class file called class.converter.php within the Models directory.
Remove the closing PHP tag (?>), this is for security reasons. This class will contain the
code that performs the conversion from miles to kilometres or kilometres to miles. Add the
following code:
class Converter {
var $number = 0, $unit = '';
public function __construct($number, $unit) {
$this->number = $number;
$this->unit = $unit;
}
public function convert() {
if ($this->unit == 'miles to km') {
$result = $this->number * 1.609;
Dave Parkinson
38. PHP5 Page 38
} elseif ($this->unit == 'km to miles') {
$result = $this->number * 0.621;
} else {
$result = 'error';
}
return $result;
}
}
Note that the new class is called Converter (the same as the filename).
This PHP file contains the following key sections of code:
class Converter {
var $number = 0, $unit = '';
This code sets up the class called Converter and declares and initialises two public
properties (number and unit).
public function __construct($number, $unit) {
$this->number = $number;
$this->unit = $unit;
}
This the constructor method for the class. When creating an instance of the class two
arguments (number and unit) are required. Within the method this takes the arguments and
assigns them to the respective properties.
public function convert() {
if ($this->unit == 'miles to km') {
$result = $this->number * 1.609;
} elseif ($this->unit == 'km to miles') {
$result = $this->number * 0.621;
} else {
$result = 'error';
}
return $result;
}
The class also contains a public method called convert. This method performs the
calculation and returns the result of the calculation.
Next we create the Controller. Either add a new php file called converter.php into the
Source File area of the project (or rename and edit the existing file page1.php). The
controller is the page visited by the user within his web browser and its purpose is to
retrieve data entered by the user and bring together the Model and the View.
Replace the contents of the file with the following code:
<?php
$view = new stdClass();
$view->pageTitle = 'Converter';
require_once('Models/class.converter.php');
Dave Parkinson
39. PHP5 Page 39
if(isset($_POST['submit'])) {
$converter = new Converter($_POST['number'], $_POST['unit']);
$value = $converter->convert();
$view->result = 'Converting ' . $_POST['number'] . ' from '
. $_POST['unit'] . ' is ' . $value . '.';
}
require_once('Views/converter.phtml');
Note that the closing PHP tag has been removed.
This PHP file contains the following key sections of code:
require_once('Models/class.converter.php');
This imports the Model which we use to perform the conversions
if(isset($_POST['submit'])) {
$converter = new Converter($_POST['number'], $_POST['unit']);
$value = $converter->convert();
$view->result = 'Converting ' . $_POST['number'] . ' from '
. $_POST['unit'] . ' is ' . $value . '.';
}
This if statement looks to see if the user has pressed the submit button. If so, a new
instance (object) of the Converter class called converter (passing the values of number
and unit submitted by the user) is instantiated. The next line creates a variable called
value and assigns it the returned value from the convert method. The next line creates the
primitive object called $view with the property result. This property is then assigned the
string of information that is to be returned to the view (e.g. Converting 5 from km to miles
is 3.105.) . This view object will be referenced in the View.
require_once('Views/converter.phtml');
This imports the View which contains the HTML that will be displayed to the user. This
View is set up as follows.
Rename the file page1.phtml to converter.phtml.
Edit the file as follows:.
<?php require('template/header.phtml') ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div>
<label>Convert </label>
<input type="text" name="number" value="<?php echo
$_POST['number']; ?>" />
</div>
<div>
<label>From </label>
<select name="unit">
<option>km to miles</option>
<option>miles to km</option>
</select>
Dave Parkinson
40. PHP5 Page 40
</div>
<div>
<input type="submit" value="submit" name="submit" />
</div>
</form>
<?php if (isset($view->result)) : ?>
<p><?php echo $view->result; ?></p>
<?php endif; ?>
<?php require('template/footer.phtml') ?>
This phtml file contains the following key sections of code:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
This is a form tag with the action attribute set to post back to itself (this is done with a
PHP statement which prints the current URL. This allows this view to be used in multiple
places on the site).
<input type="text" name="number" value="<?php echo $_POST['number']; ?>" />
This is a text input element which gets its value from the data posted back to itself. If no
data is posted back then this is NULL. This ensures that following the post the original
data inputted is still present in the text box.
<?php if(isset($view->result)) : ?>
<p><?php echo $view->result; ?></p>
<?php endif; ?>
This code tests to see if the property result within the primitive object $view has been set.
If so the result of the calculation will be displayed as shown below:
Dave Parkinson
41. PHP5 Page 41
With a web application of this nature we often want to check that the data input by the
user is valid. This can easily be done in the following manner.
We can test the value a user inputs using the PHP function is_numeric which returns
TRUE if the value is a number or a numeric string, FALSE otherwise. This can be done by
altering the function convert within the Model as follows:
public function convert() {
if (is_numeric($this->number)) {
if ($this->unit == 'miles to km') {
$result = $this->number * 1.609;
} elseif ($this->unit == 'km to miles') {
$result = $this->number * 0.621;
} else {
$result = 'error';
}
} else {
$result = false;
}
return $result;
}
This code now tests to see if the user enters a numeric value and if he does not then it
returns a value of FALSE.
Within the Controller we can modify the if statement that tests to see if the user has
pressed the Submit button as follows:
if(isset($_POST['submit'])) {
$converter = new Converter($_POST['number'], $_POST['unit']);
$result = $converter->convert();
if (!$result) {
$view->result = 'Not a valid number.';
} else {
$view->result = 'Converting ' . $_POST['number'] . ' from '
. $_POST['unit'] . ' is ' . $result . '.';
}
}
This code now tests the returned value from the convert method. If it is FALSE it displays
a message stating that the user did not enter a valid number. Otherwise it displays the
result of the calculation. Change your web application to add error checking.
2.11 Exercise 5 – A Simple Calculator
Add an additional page to your website and call it calculator. The new application should
use the techniques described previously to allow the user to perform a simple calculation.
The user should be able to enter two numbers which be added together, subtracted,
multiplied or divided, dependent upon which one of the four operators are selected by the
user from the drop down list box. On clicking the Submit button the answer should be
given on the same web page as shown below:
Dave Parkinson
42. PHP5 Page 42
2.11.1 Using the Debugger in Net Beans
With a complex program it can be very useful to run the program in single step mode and
look at the values of variables etc. at various stages of the program in order to correct any
functional errors. In order to use XDebug as a PHP debugger within Net Beans we must
edit the php.ini file within XAMPP.
Make the following changes to php.ini:
* Locate xamppphpphp.ini and make a copy of the php.ini file for editing. Name it
phpcopy.ini
* Open the php.ini file with Notepad
* Find and uncomment the line zend_extension = "xampphpext
php_xdebug.dll".
* Find and uncomment the line xdebug.remote_host=localhost. Change the
value of the setting from localhost to 127.0.0.1.
* Find and uncomment the line xdebug.remote_enable = 0. Change 0 to 1.
* Find and uncomment the line xdebug.remote_handler = "dbgp".
* Find and uncomment the line xdebug.remote_port = 9000.
* Save php.ini.
* Run the XAMPP Control Panel Application and restart the Apache
server.
Full details of how to enable XDEBUG can be found at:
http://www.netbeans.org/kb/docs/php/configure-php-environment-
windows.html#installAndEnableXDebug
One of the biggest problems with PHP development (compared to other languages) was
Dave Parkinson
43. PHP5 Page 43
the inability to add break-points and “step through” code. The PHP guru Derick Rethans
felt that PHP was missing such a useful tool, so decided to create one himself. In this
module we will only be scratching the surface of the ability of Xdebug, however it is an
invaluable tool to have in your arsenal.
Once installed, you can add break-points by clicking on the line numbers at the left hand
side of the editor. The line will then turn red to show that a break-point has been added.
To begin the debug session, you need to make sure that the project you're currently
developing is set as the “main project”, and then click on the “debug” icon.
Once it has started debugging, you get a new set icons at the top. These are: stop
debugging, continue, step over, step into, step out and run to cursor.
Depending on your Netbeans configuration, the application might automatically break at
the beginning of each file, if this is the case, just press the “continue” icon. It will then
stop at the line you have put your break-point on. And you will know that because the line
turns green.
Below the editor, there is a set of tabs. If you visit the tab called “Variables” it will show
you the state of all variables within the scope of that of the break point (including local
variables, object variables and superglobals). It tells you the variable name, the data type
of the variable and the value at that point.
Dave Parkinson
44. PHP5 Page 44
You can also hover your mouse over variables in the code and it will tell you what the
current state of them is.
From this point onwards you can use the debugging icons to control how the far through
the code the program should run, or just continue through the rest of the code (until the
next break-point if there is one).
Try the debugger within your Calculator program.
2.11.2 var_dump Function
var_dump( ) displays information about variables in a simple, readable format. This
function is very useful when debugging , providing a simple and easy way to display the
current contents of one or more variables.
For simple scalar variables (such as booleans, integers, strings, and doubles), the type of
the variable is printed, followed by an opening bracket, the value contained in the variable,
and a closing bracket.
Arrays are printed as a list of keys and values, and have their typearray) printed at the top
of the list.
Objects are handled in a fashion similar to that of arrays. The class of which the object is
an instance is displayed, followed by the typeobject). After this, a list of the object's
member variables is printed.
For example the following code:
<?php
$b = 3.1;
$c = true;
var_dump($b, $c);
?
will output to the screen
float(3.1)
bool(true)
Dave Parkinson
45. PHP5 Page 45
2.12 Maintaining Information on the Web
When you are creating an interactive web site it is often useful to be able to maintain
information entered by the user over a period of time. One way of achieving this is to use
cookies, which can save small bits of information over time on the user‟s computer.
Although cookies provide an easy way to maintain information over time they do have
limitations, they cannot be used to save objects and arrays, and the user can turn them off
in his computer web browser
To combat some of these shortcomings, PHP provides a built in object: the Session
object. The Session object is designed to maintain state for each visitor to your web site
for the duration of the visit.
The session object has the advantage over cookies in that they are able to save arrays and
objects. There is, however, one major problem with Session objects. Since they save the
information on your web server, if they are overused, they can lead to performance
problems on your web server.
2.12.1 Using Cookies
Within the client-server model, when a client wants to view a particular HTML or PHP
page he first requests the page and then once the page is found it is returned to him. At this
point the conversation between the client and the server is over. The web server does not
keep information on what clients it has spoken to recently, or what requests were made.
For this reason Web sites are often referred to as stateless (an application is said to have
state if it persists information for each user).
A web site does not have to be stateless, it can use cookies to persist information over
lengthy periods of time.
Cookies are small bits of information, such as strings and numeric values, stored on a
clients computer for a specified period of time. When cookies are created on the clients
computer, the developer needs to specify when they expire. After a cookie expires it will
automatically remove itself from the clients computer.
When a web site writes a cookie to a clients computer, only that web site can later read the
cookie‟s value. It is the browsers responsibility to keep track of which web site created the
cookie, and only allow cookies to be read by the proper web sites.
It is important to note that all modern browsers provide users with an option not to accept
cookies on their computers; however they do accept cookies by default.
Cookies are a means of saving small bits of information over time on the user‟s computer
in the form of key/value pairs. Although cookies provide an easy way to maintain
information over time they do have limitations, the major one being that the user can turn
them off in his computer web browser.
Dave Parkinson
46. PHP5 Page 46
You can set cookies using the setcookie( ) function. Cookies are part of the HTTP header,
so setcookie( ) must be called before any output is sent to the browser (i.e. before the
<html> tag). For example :-
setcookie(„firstname‟, „Dave‟);
This will send a cookie to the browser with a name of firstname and a value of Dave.
To retrieve a value from a cookie, you use the superglobal $_COOKIE. For example, to
retrieve the cookie set above into a variable you would use :-
$name = $_COOKIE[„firstname‟];
You can set the cookie parameters using the setcookie ( ) function. This function also
contains an expiration argument allow you to set the time for which the cookie is valid. If
it is not set the cookie will only remain valid until the user closes his browser. Normally
the expiration time is determined by adding a particular number of minutes or hours to the
current moment, retrieved using the time ( ) function. For example the following statement
sets the expiration time to be 1 hour from the current moment.
setcookie(„firstname‟, „Dave‟ , time()+ 3600);
Although a cookie will delete itself automatically when the expiration time is met there
may be instances when you wish to delete the cookie manually. This can be done as
follows :-
setcookie(„firstname‟, „‟);
2.12.2 Using Session Variables
PHP supports sessions. The Session object stores data types on the web server and is
accessible through any PHP page on your web site.
The Session is used to maintain state only for the duration of a users visit to your web site.
When each new user comes to your web site, memory on the Web server is allocated to
store the Session object for that user. This memory is released if the user does not visit
your web site for a certain period of time (e.g. the default for most web servers is 10
minutes, but it can be set for a shorter or longer period).
Each PHP page that uses sessions must start with the statement :-
session_start( );
Because sessions use cookies to define the user, session_start( ) must be called before any
output is sent to the browser (i.e. before the <HTML> tag). Once the session has been
registered values can be set as follows :-
$_SESSION[„name‟] = „Dave‟;
Dave Parkinson
47. PHP5 Page 47
To read the value of your Session variable into a variable in another PHP page on you site
you do the following :-
$somevariable = $_SESSION[„name‟];
The Session object uniquely identifies visitors via cookies. This means Session variables
will not persist across PHP pages if the user has cookies disabled.
Although a session will delete itself automatically when the session expires there may be
instances when you wish to delete the session, or individual session variables, manually.
This can be done as follows. To delete a session variable you can use the unset ( )
function.
unset($_SESSION[„name‟];
To delete all the session data use :-
session_destroy( );
2.12.3 Exercise 6 – Writing and Reading Cookies & Session Variables
Add an additional page to your website and call it cookies. The new page should ask you
to enter your name and age.
The PHP page should look as follows when viewed by the client :-
Your application should use the following MVC structure:
The Model (class.cookies.php) should include a class called Cookies which contains
methods to set the cookie, get the cookie and delete the cookie e.g.
Dave Parkinson
48. PHP5 Page 48
<?php
class Cookies {
public function setCookie($key, $value) {
if (strlen($value) == 0) {
$return = false;
} else {
setcookie($key, $value);
$return = true;
}
return $return;
}
public function getCookie($key) {
if (isset($_COOKIE[$key])) {
$return = $_COOKIE[$key];
} else {
$return = false;
}
return $return;
}
public function deleteCookie($key) {
if (isset($_COOKIE[$key])) {
setcookie($key, '');
$return = true;
} else {
$return = false;
}
return $return;
}
}
Note that this class does not contain a constructor, it is just a collection of methods related
to cookies that could be used on any page of your web site.
The Model (class.sessions.php) should include a class called Sessions which contains
methods to set the session variable, get the session variable and delete the session variable
<?php
class Session {
public function __construct() {
session_start();
}
public function setSession($name, $value) {
if (strlen($value) == 0) {
$return = false;
} else {
$_SESSION[$name] = $value;
$return = true;
}
Dave Parkinson
49. PHP5 Page 49
return $return;
}
public function getSession($name) {
if (isset($_SESSION[$name])) {
$return = $_SESSION[$name];
} else {
$return = false;
}
return $return;
}
public function deleteSession($name) {
if (isset($_SESSION[$name])) {
unset($_SESSION[$name]);
$return = true;
} else {
$return = false;
}
return $return;
}
}
Note that in this case a constructor is required to call the session_start( ) function.
The Controller (cookies.php) is responsible for controlling what happens when the web
page is loaded and when the Submit button is pressed. When the web page is loaded it
calls the view to display the input form. When the submit button is pressed the controller
should set the „name‟ cookie to the value typed in the textbox and should set the „age‟
cookie to the value of age typed in the textbox. It should then post to a new page called
cookiesreturn.php.
<?php
$view = new stdClass();
$view->pageTitle = 'Cookies and Sessions';
require_once('Models/class.cookies.php');
require_once('Models/class.sessions.php');
$cookies = new Cookies();
$session = new Session();
if (isset($_POST['submit'])) {
$cookies->setCookie('name', $_POST['name']);
$session->setSession('age', $_POST['age']);
header('location: cookiesreturn.php');
}
require_once('Views/cookies.phtml');
The View (cookies.phtml) is responsible for displaying the information on the web page.
It has the following structure:
Dave Parkinson
50. PHP5 Page 50
<?php require('template/header.phtml') ?>
<p>Welcome to this site. Please enter your name and age below.</p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div>
Name: <input type="text" name="name" /><br />
Age: <input type="text" name="age" /><br />
<input type="submit" name="submit" value="submit" />
</div>
</form>
<?php require('template/footer.phtml') ?>
The page cookiesreturn is used to display the data held in the cookie and the session
variable. It has the following MVC structure:
The Controller (cookiesreturn.php) is responsible for reading the values of the cookie
and session variable and passing the information to the view
<?php
$view = new stdClass();
$view->pageTitle = 'Cookies and Sessions';
require_once('Models/class.cookies.php');
require_once('Models/class.sessions.php');
$cookies = new Cookies();
$session = new Session();
$view->name = $cookies->getCookie('name');
$view->age = $session->getSession('age');
require_once('Views/cookiesreturn.phtml');
The View (cookiesreturn.phtml) displays the values of the cookie and the session
variable on the screen.
<?php require('template/header.phtml') ?>
<p>Hello <?php echo htmlentities($view->name); ?>, Welcome to this
website, you passed this value in a cookie</p>
<p>Your age is: <?php echo htmlentities($view->age); ?>. You passed
this value in a session variable</p>
<?php require('template/footer.phtml') ?>
Dave Parkinson
51. PHP5 Page 51
2.12.4 Query String
If you only need to maintain state for the duration of the users visit to your site you can
easily use cookies. However if the client has turned off cookies in his browser this method
will not work. If this is the case, and all you need to persist is simple data types, you can
pass the information in the HTTP headers using a querystring. The $_GET superglobal
variable can process information attached to the URL of the PHP page if it is formatted in
name/value pair, with each name and value separated by an equals sign (=), and each
name/value pair separated from one another by an ampersand (&). (Note that unlike using
POST to pass information, the information sent in this manner is visible to others and
there are limitations on the amount of data that can be sent)
In order to pass this information to another web page within my site all I need to do is
append the information onto the URL for the next web page. For example :-
<a href=”mynextpage.php?name=Dave&age=21”>Click for next page</a>
On the next page of the web site I can recover the information passed in the query string
using the Request object as follows :-
$strVar1 = $_GET[‘name’];
$strVar2 = $_GET[‘age’];
this will load the name and age information into two variables.
The advantage of using the this method is that it will always work regardless of how the
user configures his browser settings. Note that however as soon as the client leaves your
web site all the information is lost.
2.12.5 Exercise 7 – Passing data between PHP pages
Add an additional page to your website and call it querystring.
Create a webpage (querystring.php) containing a table with the following information:
When the user clicks on a buy link he should be sent to a new page (purchase.php) which
should show the correct information depending on which “buy” link is selected. For
example if you choose the Panasonic DVD:
Dave Parkinson
52. PHP5 Page 52
For each of the links to the “buy” page (purchase.php) you should add the Item
information and the Cost of the item to the query string associated with the link
Hints:
1. In order to create a two page web site we will need to create two Controllers
(querystring.php and purchase.php along with their corresponding Views). Note that
this particular example will not require a Model.
querystring.php Contains the require_once statement to load the View
(querystring.phtml)
querystring.phtml Contains the HTML required to display the table and the data within it
(see below)
<?php require('template/header.phtml') ?>
<table class="datatable">
<thead>
<tr>
<th>Item</th><th>Description</th><th>Cost</th><th>Purchase</th>
</tr>
</thead>
<tbody>
<tr>
<td>Sony TV</td>
<td>32" LCD Widescreen</td>
<td>£950</td>
<td>
<a href="purchase.php?item=SonyTV&cost=950">buy</a>
</td>
</tr>
<tr>
<td>Panasonic DVD</td>
<td>DVD Player</td>
<td>£80</td>
<td>
<a href="purchase.php?item=PanasonicDVD&cost=80">buy</a>
</td>
</tr>
<tr>
<td>Philips Video</td>
<td>VHS Video Recorder</td>
<td>£110</td>
<td>
<a href="purchase.php?item=PhilipsVideo&cost=110">buy</a>
</td>
</tr>
</tbody>
</table>
<?php require('template/footer.phtml') ?>
Dave Parkinson