You are on page 1of 66

Practical Internet Programming

MITxx13

Gary Stringer
Jeremy Miller
Creative Media & Information Technology

University of Exeter, UK
Practical Internet Programming: MITxx13
by Gary Stringer and Jeremy Miller

Abstract
These notes are intended to supplement the taught sessions and the textbook. If you would like me to include anything
here, please let me know.
Table of Contents
I. Programming in General ............................................................................................... 1
1. Introduction to Programming ................................................................................ 5
II. Programming in Particular ......................................................................................... 11
2. Javascript .......................................................................................................... 15
3. Javascript: Variables, Constants and Arrays ......................................................... 25
4. Introducing PHP ................................................................................................ 33
5. Variables and Constants in PHP ......................................................................... 35
6. Controlling the Program Flow ............................................................................ 41
7. Expanding the PHP Language ............................................................................ 43
8. The Interactive Web ........................................................................................... 45
9. Further Forms Processing ................................................................................... 51
10. Further programming techniques ....................................................................... 57

v
vi
List of Examples
2.1. Inserting the Date and Time .................................................................................... 18
2.2. Decisions, decisions ................................................................................................ 20
2.3. Responding to events .............................................................................................. 22
3.1. A simple array example ........................................................................................... 26
3.2. Random days of the week ....................................................................................... 28
3.3. Simple loops - the while loop .................................................................................. 30
4.1. A simple PHP example ........................................................................................... 34
8.1. A simple interactive form with Javascript ................................................................. 46
8.2. A simple validating form ......................................................................................... 48
9.1. A self-referencing form (form.php) .......................................................................... 52
9.2. A Self-referential, validating form (form2.php) ......................................................... 54

vii
viii
Part I. Programming in General
Table of Contents
1. Introduction to Programming ........................................................................................ 5
What is a computer program? .................................................................................. 5
What is a programming language? ............................................................................ 5
The Act of Programming ......................................................................................... 8
Programming and the Web ....................................................................................... 9
Programming and the Web (continued) ..................................................................... 9
Programming and the Web (continued) ................................................................... 10

3
4
Chapter 1. Introduction to Programming

What is a computer program?


• An organised set of instructions that causes a computer to behave in a prescribed manner
• Unambiguous, ordered, and with a definite outcome or terminating point
• Informal definition: a recipe written for a computer
• Formal definition: a representation of an algorithm (a set of steps that specifies how a
task is performed)
• Human readable (usually) - a.k.a. source code
• Machine readable (eventually) - e.g. machine code/native code, P-code/bytecode

What is a programming language?


• Rigidly-defined language of computer instructions
• Means of defining solutions to problems in simple steps
• Each language has its own vocabulary, syntax (rules of spelling, grammar and
punctuation that must be followed for the program to work) and semantics.

Some terms (and definitions to follow)

A programming language can be:

• Low-level or high-level
• Procedural
• Event-driven
• Object-oriented
• Compiled or interpreted
• Platform-independent or platform-specific

... and associated with a lot of jargon and buzzwords!

Low-level or high-level . is a way of describing how abstracted (removed) a programming


language is from the details of the computer.

5
Some terms (and definitions to follow)

• Low-level programming languages, such as machine code (often known as the first-generation
language, or 1GL) and assembly language (2GL), were the first programming languages to
be developed. Closely tied to the computer hardware, they require little or no translation in
order to run on the computer. However, they are challenging for the programmer on account
of their dissimilarity with natural human language and the number of detailed steps required
to implement even a simple program.

• High-level programming languages were developed from the 1950s onwards to provide a
more effective means of writing computer programs. These languages are more similar to
natural human languages and provide a greater level of abstraction, which can make problems
easier to solve. One downside of this is that, at some point, a program written in a high-level
language needs to be translated into a form that the computer can understand (see 'Compiled
or interpreted' below).

• Javascript and PHP, the programming languages we will be using in this module, are both
high-level languages (phew!).

A procedural language. allows programs to be written in a more structured, modular form.

• Program statements that perform a particular task can be grouped together in a named section
called a procedure. Use of procedures (also known as routines, functions or methods) can
make programs more maintainable and extensible (extendable) and encourage code re-use.

• Most modern high-level programming languages, including PHP and Javascript, support
procedural programming, but the extent to which a given program is procedural is often in the
hands of the programmer.

• Procedural programming is a development of an earlier form of programming called


sequential programming or batch programming. In sequential programming, program code
takes the form of a sequence of statements which are executed (actioned) in an order
predetermined by the programmer.

An event-driven language. is one in which the flow of the program responds to actions of
the user or in response to other events (e.g. messages from other programs or the computer's
operating system).

• Event-driven programs places the user rather than the programmer in control.

• Program statements still executed in sequence, and may be grouped into procedures, but run
in response to specific events.

• Examples of event-driven programming languages include Javascript, Visual Basic and Java.

An object-oriented language. is one in which data and program logic are contained in a
single software component called an object.

6
Some terms (and definitions to follow)

• Other code can access an object's data by referring to a property of the object or make it behave
in a certain way by calling one of its predefined procedures, known as a method.

• The way the object actually store its data and take its decisions is hidden from external code.

• This controlled access can make it easier to share data and get programs to work together.

• Object and its methods are described in a blueprint or template known as the object's class.

• In object-oriented (as opposed to object-based) languages, new classes of object can be derived
from existing classes of object (known as inheritance), facilitating very effective code reuse.

• Examples of object-oriented languages include C++, Java and versions 5 and 6 of PHP.
Javascript is generally referred to as an object-based language, because it does not support
true inheritance.

A compiled language. is one which the source code written by the programmer must be
translated into machine code that the computer can run directly

• A tool known as a compiler is used to translate the source code into a machine code that the
target computer can understand and execute.

• The resulting machine code program may be called an executable or a binary.

• Main advantage of compiled languages is their speed of execution.

• Disadvantages include the need to compile in advance, greater development time, platform-
dependence.

• C++, Java and Visual Basic .NET are compiled languages.

An interpreted language. is one which runs more directly on the computer and does not
have an explicit compilation step.

• A program in an interpreted language seems to run without compiling, but the source code is
actually translated into machine code at the time of execution.

• A program known as an interpreter (or occasionally virtual machine) is used to perform this
"on the fly" translation.

• Advantages of interpreted languages include platform-independence, easier development and


debugging, smaller program size.

• Main disadvantage of interpreted languages is their speed of execution.

Platform dependence/independence.

• Programming languages vary in how dependent they are on the specific hardware and
operating system of a computer, known as a platform.

7
The Act of Programming

• Some languages are designed to produce programs primarily for a particular hardware and
software setup and are said to be platform-dependent.

• Examples of platform-dependent languages include Microsoft Visual Basic and C# which


target Intel x86 or compatible computers running the Microsoft Windows operating system.

• Other languages are more platform-independent. Examples include Java, PHP and Javascript,
all of which can be used to write programs that will run on a variety of hardware and software
set-ups.

The Act of Programming


• Programs can be written manually using

• Text editors (e.g. Windows Notepad, ConTEXT, EditPlus, Notepad++, TextPad,


BBEdit) plus compilers (if needed and not included in text editor).

• Code editors (e.g. jEdit, Programmer's Notepad)

• Integrated development environments (IDEs), which combine code editors with other
features to help the programmer. Examples include Delphi, C++ Builder and Eclipse.
• In some languages, programs can be written visually using drag-and-drop WYSIWYG
editors

• Useful for constructing the graphical user interface (GUI) of a program.

• Also known as GUI builders and found in some IDEs.

• Examples include Microsoft Visual Studio and NetBeans.

How is a program made?

• Compiled languages (e.g. Java)


• Write the program
• Compile it to create an object file containing macine code.
• Run the object file
• Interpreted languages (e.g. Javascript, PHP)
• Write the program
• Run the program, which is “interpreted” as it runs

8
Programming and the Web

Programming and the Web

• Adding dynamic elements to the Web

• HTML and XHTML pages are static - no real interactivity with the user.

• Web programming languages such as Javascript and PHP can be used to add
interactivity to HTML/XHTML.

• Examples include responding to mouse and keyboard actions, checking user input,
building web pages dynamically, inputting and displaying data, etc.

Programming and the Web (continued)

• Programming v. Scripting

• Not a concrete distinction, but...

• Programming languages generally have stricter rules of syntax, often need to be


compiled, and usually produce code that can run more or less independently of other
software.

• Scripting languages are generally less strict about syntax, are usually interpreted rather
than compiled, and often produce code that works with another application (e.g. a
web browser or a web server).

• Most newcomers find scripting languages easier to learn.

• Javascript and PHP (in its usual form) are both scripting languages - hurray!

9
Programming and the Web (continued)

Programming and the Web (continued)

• Client-side vs. Server-side

• Client refers to the end-user's computer or a program running on that computer.

• Server refers to a central computer (or a program running on a central computer) that
clients connect to and interact with.

• Clients and servers connect via the Internet or a local network such as an intranet.

• Differences between client-side and server-side are important when programming for
the World Wide Web.

• In most cases, creating a dynamic web site requires both client-side programming
(e.g. Javascript) and server-side programming (e.g. PHP).

10
Part II. Programming in Particular
Table of Contents
2. Javascript .................................................................................................................. 15
What is Javascript? ................................................................................................ 15
Javascript: What can it do? .................................................................................... 15
Javascript: What can't it do? ................................................................................... 16
Javascript: What can you do with it? ...................................................................... 16
How do I write Javascript? ..................................................................................... 17
Getting started - Simple dynamic elements .............................................................. 18
Controlling sequence of instructions ....................................................................... 20
Event driven programs ........................................................................................... 22
3. Javascript: Variables, Constants and Arrays ................................................................. 25
Storing information ................................................................................................ 25
Arrays - collections of variables ............................................................................. 25
Adding a random element ...................................................................................... 27
Javascript: Controlling the program ........................................................................ 29
4. Introducing PHP ........................................................................................................ 33
How do I write PHP? ............................................................................................ 33
5. Variables and Constants in PHP ................................................................................. 35
Variables ............................................................................................................... 35
Constants ............................................................................................................... 36
Arrays ................................................................................................................... 37
Creating HTML lists .............................................................................................. 38
Some Syntax Details .............................................................................................. 39
6. Controlling the Program Flow .................................................................................... 41
Ifs and Elses .......................................................................................................... 41
Loops .................................................................................................................... 42
7. Expanding the PHP Language .................................................................................... 43
8. The Interactive Web .................................................................................................. 45
Creating XHTML forms ......................................................................................... 45
Creating interactive forms ...................................................................................... 45
Accessing the HTML document elements ................................................................ 47
Making the form respond to inputs ......................................................................... 47
Retaining data in the form ...................................................................................... 49
9. Further Forms Processing ........................................................................................... 51
Creating forms that call themselves ........................................................................ 51
More validation patterns ......................................................................................... 53
10. Further programming techniques ............................................................................... 57
Sharing Common Code across a Website ................................................................ 57
Security ................................................................................................................. 57

13
14
Chapter 2. Javascript
What is Javascript?
• A client-side scripting language for web browsers
• A simple way to add interactivity to web pages

N.B. Javascript is not Java. Javascript was first developed by Netscape Communications
in the mid-1990s to enable HTML authors to enhance and add basic user interaction to
HTML pages displayed in the Netscape Navigator web browser. The original name of the
language was LiveScript, but this was changed (confusingly) to JavaScript in 1995 in honour
of Sun Microsystems, creator of the Java programming language, who had joined Netscape in
developing the LiveScript language.

Since these early days, the use of Javascript (or rather versions of Javascript) has become
increasingly commonplace in web development, and the language is now a standard feature on
nearly every browser (although it can be turned off!)

However, it is important to realise that Javascript and Java are two completely different
languages. Javascript is a lightweight, interpreted client-side scripting language that is used to
add interactivity to web pages. Java is a fully-featured complied programming language that
is equally good at writing client-side and server-side programs and isn't dependent on a web
browser to run.

Javascript: What can it do?


Here are some of the main programming features that Javascript supports:

• Javascript supports standard programming constructs such variables, loops, decision-


making, etc.
• Javascript supports objects. It has an extensive library of built-in objects including
browser windows, frames, links, forms, form elements (such as buttons), etc. You can
also create your own objects.
• Javascript supports functions, which are procedures that do work and return a value.
Javascript has some built-in functions (e.g. parseInt() translates a numeric string into a
whole number) or you can create your own.
• Javascript is an event-driven language. You can write a block of Javascript code that
does something in response to the action of the user, e.g. open a new browser window
when a user clicks on a button.

15
Javascript: What can't it do?

Javascript: What can't it do?

Some features that Javascript does not support:

• Javascript cannot create standalone programs. Code written in Javascript can only run
within a Web browser that supports it.
• Javascript cannot open local files or network connections. This ensures user security,
but limits the degree to which Javascript can interact with users.
• Javascript’s syntax and runtime error-checking abilities are very limited, although
there are some tools to help (e.g. the Firebug [https://addons.mozilla.org/en-US/firefox/
addon/1843] add-on for the Mozilla Firefox

Javascript: What can you do with it?

Given its capabilities and limitations, here are some tasks for which Javascript is well
suited:

• Enabling users to interact with HTML pages. Javascript code can respond directly to
user interaction with <FORM> elements (text boxes, buttons, check boxes, drop-down
selection lists, and so on), images, and hypertext links.
• Validating data on the client before submitting it to the server (but don't rely on it!).
• Spicing up web pages with the date, time, status bar messages, scrolling banners, and
so on.
• In combination with XML (Extensible Markup Language) and server-side languages
such as PHP, providing the sort of rich, dynamic client-side experience associated with
websites such as Google Maps [http://maps.google.com/] and GMail [http://gmail.com/
]. This technology is known as AJAX (Asynchronous Javascript and XML) and we will
look at it briefly at the end of the course if we have time.

16
How do I write Javascript?

How do I write Javascript?

• Incorporated in the (X)HTML of the web page, in the <head> </head> or


<body> </body> section.
• Ideally, the web page should conform to the XHTML 1.0 Strict guidelines - http://
www.w3.org/TR/xhtml1/
• Use a template [http://services.exeter.ac.uk/cmit/modules/programming/examples/
workshop_1/template.html] or configure your editor to create new web
pages as XHTML 1.0 Strict, e.g. Dreamweaver: Edit--> Preferences--
> New Document [http://services.exeter.ac.uk/cmit/modules/programming/figures/
dw_new_doc_preferences.gif]
• Marked out by <script type="text/javascript"> </script> tags
• Some HTML attributes use Javascript (e.g. onclick, onload, etc)

17
Getting started - Simple dynamic elements

Getting started - Simple dynamic elements


Example 2.1. Inserting the Date and Time

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=utf-8" />
<title>Javascript Example: Dates and Times</title>
</head>
<body>
<h1>Javascript Example: Dates and Times</h1>
<script type="text/javascript">
<!--
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();

document.write("<p>The time is " + hour +


":" + minute + ".</p>");
//-->
</script>
</body>
</html>

What does this show?

• Use of the <script> tag

• Use of (X)HTML comments tags <!-- --> to hide script from older browsers that don't
understand Javascript.

• The two forward slashes at the end of comment line (//) are the JavaScript comment symbol.
This prevents JavaScript from executing the --> tag.

• A sequence of instructions, executed in order.

• Each program statement must be terminated by a semicolon.

18
Getting started - Simple dynamic elements

• Use of variables to store information temporarily (e.g. the date or hour)

• Use of a method to get further information (e.g. getHours)

• A way of writing HTML to the document (document.write)

Now try this...

1. Using the methods getDate(), getMonth() and getFullYear(), write the date
below the time.

2. Why is the month value always a month behind?

3. What do the functions getDay() and getYear() do?

For further help with dates in Javascript, check out the W3Schools page on the Date object -
http://www.w3schools.com/js/js_obj_date.asp

19
Controlling sequence of instructions

Controlling sequence of instructions


Example 2.2. Decisions, decisions
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=utf-8" />
<title>Night and Day Script</title>
</head>
<body>
<script type="text/javascript">
<!--
var now = new Date();
var hour = now.getHours();

if (hour >= 4 && hour <= 18) {


document.bgColor = "#FFFFFF";
document.fgColor = "#000000";
document.write("<p>Good day, and isn't it a lovely day?</p>");
}
else {
document.bgColor = "#000000";
document.fgColor = "#FFFFFF";
document.write("<p>Good evening.</p>");
}
//-->
</script>
</body>
</html>

This example shows:

• Tests and comparisons

• Combining tests (&&)

• Making decisions (if (test) { ... } else { ... } )

• Groups or blocks of instructions

20
Controlling sequence of instructions

Now try this...


1. Modify the program to respond to morning, afternoon and evening.

21
Event driven programs

Event driven programs


Example 2.3. Responding to events

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=utf-8" />
<title>Javascript Example: Events</title>
<script language="javascript">
<!--
var now = new Date();
var daydate = now.getDate();
var month = now.getMonth();
var year = now.getFullYear();
var todaysdate = "" + daydate + ":" + (month+1) + ":" + year;
//-->
</script>
</head>
<body>
<h1>Javascript Example: Events</h1>
<form id="form1" name="form1" method="post" action="">
<p>
<label>Date:
<input type="text" name="date" id="date" />
</label>
<input type="button" name="todaybutton"
id="todaybutton" value="Insert today's date"
onclick="getElementById('date').value=todaysdate"/>
</p>
<p>
<input type="submit" name="submitbutton"
id="submitbutton" value="Submit" />
</p>
</form>
</body>
</html>

22
Event driven programs

This example shows:

• Javascript embedded as HTML attributes

• Initialising a variable for later use

Now try this...


1. Add a similar text field and button to enter the time.

23
24
Chapter 3. Javascript: Variables, Constants and Arrays

• Storing information
• The shape of information
• Storing multiple data items

Storing information

• Variables are used to store data

• Data-shaped - may be strings, integers, floats, boolean, etc.

Many programming languages use a very rigid scheme for creating and storing data, based on
the type of data to be stored. These are called strongly typed languages, and they force the
programmer to think very carefully about the “shape” of the data being used. For example, in a
strongly typed language, the variable used to store a whole number (or integer) will be a different
shape (or type) to one used to store a decimal (or floating point) number.

In Javascript, and to some extent in PHP, the rules are much more relaxed, and often, different
types of data can be used interchangeably.

Arrays - collections of variables

• An ordered collection of variables...


• ... which can then be treated as a single object

25
Arrays - collections of variables

Example 3.1. A simple array example

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=utf-8" />
<title>Javascript Example: Dates and Times</title>
</head>
<body>
<h1>Javascript Example: Dates and Times</h1>
<script language="Javascript">
<!--
var daysofweek = new Array();
// note that the array starts with zero = Sunday
daysofweek[0] = "Sunday";
daysofweek[1] = "Monday";
daysofweek[2] = "Tuesday";
daysofweek[3] = "Wednesday";
daysofweek[4] = "Thursday";
daysofweek[5] = "Friday";
daysofweek[6] = "Saturday";
// and the array ends with six = Saturday

var now = new Date();


var daynum = now.getDay();

document.write("<p>Hello, what a lovely "


+ daysofweek[daynum] + " this is.</p>");
-->
</script>
</body>
</html>

This example illustrates:

• Basic construction of an array


• Arrays may begin with [0] as their first item
• Array elements can be referenced using [ ]

26
Adding a random element

Now try this...


1. Add another array that stores the names of the months of the year, and output the full date
in the form “Wednesday 5 November 2008”.

Adding a random element

• Math() object in Javascript

• Has a range of properties and methods that allow you to perform mathematical tasks.

• Properties include Math.PI [ratio of a circle's area to the square of its radius,
approximately 3.14159] and Math.SQRT2 [the square root of 2, approximately
1.414].

• Methods include Math.random() [returns a random number between 0 and 1] and


Math.sqrt(x) [returns the square root of a number].

• Unlike some other objects in Javascript (e.g. Date object), it is not necessary to create
a Math object before using one of its properties or methods.

• For more on the Math object, see http://www.w3schools.com/jsref/


jsref_obj_math.asp
• To generate a random whole number in a particular range use the random() and
floor() methods of the Math object as follows:

1. Get a random floating point number between 0 and 0.99999999999999999 using the
Math.random() method

2. Multiply this by the number of values you require.

3. Use Math.floor() to remove the decimal fraction and leave just the integer part
of the result.

4. (OPTIONAL) Add an offset if you don't want zero as the first possible number.

27
Adding a random element

Example 3.2. Random days of the week


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=utf-8" />
<title>Javascript Example: Dates and Times</title>
</head>
<body>
<h1>Javascript Example: Dates and Times</h1>
<script language="Javascript">
<!--
var daysofweek = new Array();
// note that the array starts with zero = Sunday
daysofweek[0] = "Sunday";
daysofweek[1] = "Monday";
daysofweek[2] = "Tuesday";
daysofweek[3] = "Wednesday";
daysofweek[4] = "Thursday";
daysofweek[5] = "Friday";
daysofweek[6] = "Saturday";
// and the array ends with six = Saturday

var now = new Date();


var daynum = now.getDay();

// Generate a random whole number between 0 and 6


var favourite = Math.floor(Math.random() * 7);

// Alternatively, broken down, step-by-step...


// var favourite = Math.random();
// alert('Math.random()\n' + favourite);
// favourite = favourite * 7;
// alert('Math.random() * 7\n' + favourite);
// favourite = Math.floor(favourite);
// alert('Math.floor(Math.random() * 7)\n' + favourite);

document.write("<p>My favourite day of the week is " +


daysofweek[favourite] + " (" + favourite + ").</p>");
-->
</script>
</body>
</html>

28
Javascript: Controlling the program

Press “Refresh” to generate a new day...

This script also shows:

• Arithmetic operators ( + - * / ) - for more see the 'JavaScript Arithmetic Operators' section
at http://www.w3schools.com/js/js_operators.asp

• Math.floor() method rounds down to the next whole number (http://


www.w3schools.com/jsref/jsref_floor.asp).

• Other methods of the Math object can also be used for rounding numbers, e.g.

• Math.ceil() rounds up to the next whole number (http://www.w3schools.com/jsref/


jsref_ceil.asp).

• Math.round() rounds up or down to the nearest whole number (http://


www.w3schools.com/jsref/jsref_round.asp).

Now try this...


1. Use the daynum variable to print a message when the 'favourite' day matches today's day
of the week.

Javascript: Controlling the program

• Repeating { groups of actions }

• Uses conditions (see the if () example earlier)

29
Javascript: Controlling the program
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Example 3.3. Simple loops - the while loop
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=utf-8" />
<title>Javascript Example: Dates and Times</title>
</head>
<body>
<h1>Javascript Example: Dates and Times</h1>
<script language="Javascript">
<!--
var daysofweek = new Array();
// note that the array starts with zero = Sunday
daysofweek[0] = "Sunday";
daysofweek[1] = "Monday";
daysofweek[2] = "Tuesday";
daysofweek[3] = "Wednesday";
daysofweek[4] = "Thursday";
daysofweek[5] = "Friday";
daysofweek[6] = "Saturday";
// and the array ends with six = Saturday

// generate a random number between 0 and 6


var favourite = Math.floor(Math.random() * 7);

var i = 0; // a counter used to step through the days

// now step through the days


while (i < 7) {
document.write("<p>" + daysofweek[i]);

// check if the day matches our favourite day


if (i==favourite) {
document.write(" <em>(my favourite)</em>");
}
document.write("</p>");

// add one to the counter


i++;
} // end the while loop
-->
</script>
</body>
</html>

30
Javascript: Controlling the program

Notes

• The while loop uses a condition in the same way as an if (), but with repetition:

• the following block (within { } ) is repeated while the condition is true

• here, the block also includes an if () statement

Now try this...


1. Investigate the do {....} while () loop. What is the difference between this
and a simple while () {.....}? Any problems, consult W3Schools (http://
www.w3schools.com/js/js_loop_while.asp)

2. Investigate the for loop. What is the difference between this and a while loop? Again,
for more information, see the W3Schools help topic at http://www.w3schools.com/js/
js_loop_for.asp

31
32
Chapter 4. Introducing PHP

• Originally designed to automate web page creation


• Mainly used for server-side scripting
• Can be used to create desktop applications too

The name “PHP” originally stood for “Personal Home Page”, and was developed by Rasmus
Lerdorf to automate parts of his home pages. When he published its capabilities, it quickly gained
popularity and has now become a standard language for web development, powering some of
the most prominent sites on today's web.

This growth has changed the meaning of the language's acronym, which today is usually taken
as "PHP Hypertext Preprocessor", a strangely circular definition, but one which highlights the
language's mode of operation, where PHP commands embedded in standard web pages are
preprocessed before being sent to the web browser.

How do I write PHP?

• Incorporated into the (X)HTML


• Marked out by <?php php command(s) ?>
• Small snippets or whole pages

PHP is designed to be very simple to include into (X)HTML web pages, but it also has features
common to more heavyweight languages, which means it can be used to construct very powerful
and complex web applications.

33
How do I write PHP?

Example 4.1. A simple PHP example

<!DOCTYPE html PUBLIC


"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Hello, World!</title>
</head>
<body>
<?php echo "<h1>Hello, World!</h1>"; ?>
</body>
</html>

Notice the following points:

• PHP is embedded in HTML


• HTML can be embedded in PHP output
• PHP shares many common features with Javascript
• ...but many commands differ (e.g. echo vs. document.write)

34
Chapter 5. Variables and Constants in PHP
As our programs run, we often need to store intermediate calculations or temporary values within
the program. To do this, we need to use variables, which act as temporary storage slots within the
computer's memory. They can be used to store a variety of types of data, though once a variable
has been created, its shape is fixed, and can only store the same type of data as its original value.
With a variable, it's possible to change the data it contains later, but sometimes you need to ensure
that a value doesn't change throughout the program - for this you can use a constant.

Variables
At a basic level, variables can store either numbers or strings. Many computer languages (called
strongly-typed languages) insist on particular shapes of data within this (so numbers might be
restricted to integers (whole numbers) or floats (decimal fractions) and many more). PHP is much
more liberal, and you can use variables to store whole and fractional numbers equally well - a
number is just a number.

So how do we create a variable?

<?php $myfavouritenumber = 7; ?>

Here we have created a new variable called myfavouritenumber, and stored the value 7
in it. One major difference from Javascript is that the name of the variable must start with the
$-sign, and must be composed of letters and/or numbers. You can also use the _ character to
separate words in the name, or use capital letters to do the same.

You can add numbers and variables together, subtract them, multiply and divide them (note that
multiply is represented by *). So:

<?php
$result = 83 + 76;
$double = $result * 2;
$average = ($a + $b + $c + $d)/2;
?>

String variables are similar, but they hold an amount of text:

<?php $myname = "Fred Bloggs"; ?>

35
Constants

Note that the string itself is surrounded by quote marks (you can use either the single ' or double
" marks). This is called a string literal.

You can combine strings, though be careful to use the '.' for PHP, as opposed to the '+' for
Javascript, thus:

<?php $myname = $myfirstname." ".$mysurname; ?>

As with the Javascript example, we need to add extra space as string literals so that it looks better
when printed out.

Constants
Sometimes, we need to ensure that a value stored in the program is not changed, though, and
for this we can use a constant. In PHP, constants are usually written in ALL_CAPITALS to
distinguish them from normal variables:

<?php
define ("PI",3.1415927);
define ("VAT",0.175);
define ("AUTHOR","Fred Bloggs");

$circle_area = $PI * ($circle_radius * $circle_radius);


$total_cost = $net_cost + ($net_cost * $VAT);

echo "The author of this program is ".$AUTHOR;


?>

Notes

In fact, there is a PHP function pi() which returns the value of pi, and a power function
pow(x,y), so we could write

$circle_area = pi()*pow($circle_radius,2);

36
Arrays

Arrays
Often, we wish to gather a whole collection of variables, and treat them as one single storage
area. One way of doing this is an array, which can be visualised as a row or grid of storage slots,
each holding a number or string value. Here's an array:

<?php $daysofweek = array ('Monday','Tuesday',


'Wednesday','Thursday','Friday',
'Saturday','Sunday');
?>

Now we can refer to items stored in this array by number:

<?php echo $daysofweek[0]; ?>

which will output Monday, since arrays always begin at zero if you don't specify otherwise.

If we want to begin the array with a different index other than zero, we need to specify this when
we create the array:

<?php $daysofweek = array (1=>'Monday',2=>'Tuesday',


3=>'Wednesday',4=>'Thursday',5=>'Friday',
6=>'Saturday',7=>'Sunday');
?>

This can also be abbreviated to:

<?php $daysofweek = array (1=>'Monday','Tuesday',


'Wednesday','Thursday','Friday',
'Saturday','Sunday');
?>

But the main advantage of using an array rather than simple variables is that the whole array can
be worked on at once, so for example:

<?php asort($daysofweek); ?>

37
Creating HTML lists

will sort all the days we have stored in the array into alphabetical order.

And we can process the individual slots more efficiently too:

<?php
foreach ($daysofweek as $dayname) {
echo $dayname:
}
?>

which will print the days of the week out into the page.

Questions
1. How can we make this list look “prettier”? Try adding spaces between the names of the
days.

2. Next add some HTML markup to turn it into a proper <ol> list.

Creating HTML lists


A useful technique with arrays is to turn them into a variety of HTML constructs, such as lists
or tables. Try this in the <body> of your PHP document:

<?php
$daysofweek = array (1=>'Monday','Tuesday',
'Wednesday','Thursday','Friday',
'Saturday','Sunday');
echo "<ol>";
foreach($daysofweek as $index => $dayname) {
echo "<li>".$index.". ".$dayname."</li>";
}
echo "</ol>";
?>

Now try this...


1. How can we create an HTML table in a similar way?

38
Some Syntax Details

Here's one way of achieving this:

<?php
$daysofweek = array (1=>'Monday','Tuesday',
'Wednesday','Thursday','Friday',
'Saturday','Sunday');
echo "<table border='1'><tbody>";
foreach($daysofweek as $index => $dayname) {
echo "<tr><th>".$index."</th><td>".$dayname."</td></tr>";
}
echo "</tbody></table>";
?>

Some Syntax Details


You'll have noticed by now that the syntax (the grammar of PHP) is quite specific and pedantic - a
semicolon in the wrong place will often produce an error message. So how does this syntax work?

; (semicolon) officially, the semicolon separates adjacent commands


or blocks, though many programmers use them to terminate
commands (additionally writing a semicolon after the last
command in a block).

{ } (braces) groups together a set of commands as a block. Often used


in control structures (see the foreach example above).

<!-- and --> (comments) are used to mark out comments or remarks within the
program, to document a feature or to remind the author to complete
or amend something.

39
40
Chapter 6. Controlling the Program Flow

Ifs and Elses


Often we need to perform a particular action based upon a decision or calculation within the
program. To do this, we can use the if statement, which looks like this:

<?php if (test) { ...commands... } ?>

where the test is the decision itself, and the ...commands... are the program commands to be
executed if the decision is true. So, we might have:

<?php
if ($myname == "Fred Bloggs") {
echo "<p>Hello, Fred! How are you?</p>";
}
?>

As with Javascript, there's an else which can be used:

<?php
if ($myname == "Fred Bloggs") {
echo "<p>Hello, Fred! How are you?</p>";
} else {
echo "<p>Who are you?</p>";
}
?>

With PHP, where an if follows an else, the else if is combined into one command:

<?php
$hour = date("h");
if ($hour > 4 && $hour < 12) {
echo "<p>Good morning.</p>";
} elseif ($hour >= 12 && $hour < 17) {

41
Loops

echo "<p>Good afternoon.</p>";


} else {
echo "<p>Good evening.</p>";
}
?>

Note: The arguments for the date() function can be found listed at W3Schools
[http://www.w3schools.com/php/func_date_date.asp]; these can be combined, so that
date("d:m:y") gives us “30:10:07” and date("D, d M, Y") will produce “Tue, 30
Oct, 2007”.

There are a number of operators that can be used in the test; there is a useful summary [http://
www.w3schools.com/php/php_operators.asp] on the W3Schools website.

Loops
Review the control structures we looked at last week for Javascript, and check the textbook for
their equivalents in PHP (they're very similar). Try to program last week's examples in PHP.

Note that there is an equivalent random number function to Math.random()in PHP, called
rand(), but it needs a maximum and minimum value, and generates whole numbers. So
rand(1,100) will give a random whole number between 1 and 100 inclusive.

42
Chapter 7. Expanding the PHP Language
One of the most powerful features of programming languages in general is the ability to expand
the command language, by creating new functions. With this feature, we can create named blocks
of commands that can be called at will, and even given information to process.

Here is the basic form of a function:

function myfunction() { ...commands...};

where myfunction is the name of the function, and ...commands... are the commands to be called
when we execute the function in a program. An example of this simplest form of function could
be a routine that prints out a greeting:

function greet() {
echo "Hello.";
}

where calling the function within the program will print the greeting to the PHP page:

echo "<p>";
greet();
echo "</p>";

We can also give the function one or more arguments, which effectively pass data to the function
for processing. So:

function myfunction($argument) { ...commands... };

specifies an argument called $arg; this sets a variable that only exists within the function. The
variable $arg is created each time the function is called, and is initialised with the value in the
rounded brackets when called. So:

function printName($name) {
echo $name;
}

43
can be called with

echo "<p>Your name is ";


printName("Fred Bloggs");
echo "</p>";

We can also use return to send a result back to the main program, allowing us to use the
function as if it were a literal or variable:

function doubleIt($value) {
$result = $value * 2;
return $result;
}

echo "Doubling 16 gives ".doubleIt(16).".";

so this would print the string Doubling 16 gives 32.

44
Chapter 8. The Interactive Web

• Form elements and form processing


• Introducing the Document Object Model (DOM)
• Interactive forms
• Prerocessing form data and validation

Creating XHTML forms

• The <form> element


• Form components
• Form actions
• Creating an interface

Creating interactive forms

• Using Javascript to pass data around


• Using Javascript to enable/disable form elements
• Thinking about valid sets of inputs for a form

45
<title>Enabling and Disabling Form Elements</title>
<script language="javascript">
function disableOtherColour() {
document.form1.otherColour.disabled=true;
return true;
}
Creating interactive forms
function enableOtherColour() {
document.form1.otherColour.disabled=false;
Example 8.1. A simple interactive form with Javascript
return true;
}
</script>
</head>

<body>
<form id="form1" name="form1" method="post" action="">
<fieldset><legend>Choose a colour</legend>

<input type="radio"
name="colourSelector"
id="colourSelectorBlue"
value="blue"
onclick="disableOtherColour();"/>
<label for="colourSelectorBlue">Blue</label>
<br />
<input type="radio"
name="colourSelector"
id="colourSelectorOrange"
value="orange"
onclick="disableOtherColour();"/>
<label for="colourSelectorOrange">Orange</label>
<br />
<input type="radio"
name="colourSelector"
id="colourSelectorOther"
value="other"
onclick="enableOtherColour();"/>
<label for="colourSelectorOther">Other (give details):</label>

<input type="text"
name="otherColour"
id="otherColour"/>
<br />

</fieldset>
</form>
</body>
</html>

46
Accessing the HTML document elements

Now try this....


1. Add another radio button for "Green".

Accessing the HTML document elements

• The Document Object Model


• Using the direct reference (e.g. document.form1...)
• Using getElementById()

We saw an example of the use of getElementByID() in the Example 2.3, “Responding to


events”. This is usually more reliable than using a direct path, as it means that if the form is
renamed or the form elements are moved around, the script will continue to work.

Making the form respond to inputs

47
} elseif (strpos($domain,'.')==0) {
return 'Please ensure your email address has a valid domain name.';
} else {
return ''; // Empty string indicates no error!
}
}
Making the form respond to inputs
?>
Example 8.2. A simple validating form
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1" />
<title>PHP: Adaptive Forms Example</title>
</head>

<body>
<form id="form1" name="form1" method="post" action="">

<p>
<label>Your full name:
<input name="name" type="text" size="48" />
</label>
</p>

<p>
<label>Email address:
<input name="email" type="text" size="48" />
</label>

<?php
if ($_POST["Submit"]) {
$myresult = check_email($email);
if ($myresult=='') {
echo "<span style='background-color:green'>Valid.</span>";
} else {
echo "<span style='background-color:red'>".$myresult."</span>";
}
}
?>
</p>
<p>
<input type="submit" name="Submit" value="Submit" />
<input name="Reset" type="reset" id="Reset" value="Reset" />
</p>
</form>
</body>
</html>

48
Retaining data in the form

Note that we have still set the action="", which means that the form will send the data to
itself. This is common for a validating form such as this, where the form needs to be redisplayed
to show the errors when validation fails. In a real-world example, there would be a further action
which would redirect the page to a confirmation or thank-you page, which would process the
form data in some way.

We have also placed some PHP code before the !DOCTYPE and html root element of the
document. Here, this code could equally go in the head element (or elsewhere), though
sometimes it's necessary to initialise things before any data is sent to the web browser.

Now try this...


1. Add another function, check_name(), which checks that some text has been entered
into the 'Full Name' text box.

2. Modify this new function to test whether more than one name (e.g. firstname and surname)
has been entered.

Retaining data in the form


Note that the form elements include some data "echoed" into them, so that if the form has already
been submitted, the user won't have to retype it ... this is referred to in the book as “making the
data sticky”.

<label>Your full name:


<input name="name" type="text" value="<?php echo $name; ?>" size="48" /
</label>

...

<label>Email address:
<input name="email" type="text" value="<?php echo $email; ?>" size="48"
</label>

49
50
Chapter 9. Further Forms Processing
In this chapter, we'll look a little more closely at some of the form actions, and examine how to
respond to different situations presented to us when processing forms data.

Creating forms that call themselves

• Forms usually point to an "action" program that processes the data they contain.
• But, if action is blank, the form is self-referencing:
• i.e. the form is its own action
• so, the page must adapt to respond to the data
• the page may show different views according to the data

51
</head>
<body>
<?php if (isset($_GET["Submit"])) { //beginning of "if submitted else" bl

/* this section only runs when the page is responding if the


Submit POST variable is set, i.e. the Submit button has
been pressed. Creating forms that call themselves
*/
?>
Example 9.1. A self-referencing form (form.php)
<h1>You chose the colour

<?php

switch ($_GET["colourbuttons"]) {
case "red":
echo "red";
break;
case "blue";
echo "blue";
break;
} ?>
</h1>
<p><a href="form.php">Choose again!</a>
<?php
} else { // else clause of "if submitted else" block

/* this section only runs when the page is loaded without


a form response, i.e. the $_GET["Submit"] is not set.
This will be the case when the form is initially loaded.
*/

?>
<form id="colourform" name="colourform" method="get" action="">
<p>Choose a colour:
<label>
<input type="radio" name="colourbuttons" id="colourbuttonred" value="
Red</label>
<label>
<input type="radio" name="colourbuttons" id="colourbuttonblue" value=
Blue</label>
<input type="submit" name="Submit" value="Submit" />
</p>
</form>

<?php } // end of the "if submitted ... else" block


?>
</body>
</html>

52
More validation patterns

Points to note:

• Page divided into one large if ... else ...


• Test checks whether the "Submit" button is pressed
• uses isset() to test if variable exists
• note that if statement is not contained in a single <?php ... ?> block, but is mixed
with XHTML elements too
• Can use GET or POST, but GET is more visible for testing!

• The switch { case .... } handles each possible response
• Note mixing of PHP and HTML again

Now try this...


1. Add a couple more colours to the form.

2. What happens if no button is selected? Add a response for this situation.

3. Change the colour of the text according to the colour selected.

Hint: you could use PHP to write a style="color:red" attribute to the <h1> element.

4. Change the background colour of the page according to the selection.

Hint: the easiest method is to give the <body>


element of the document an id="mybody" attribute, then use
document.getElementById("mybody").style.backgroundColor to set
the CSS background colour.

You could also use PHP to write style information in the <head> of the document, or to
write an attribute directly to the body element.

More validation patterns

• Introducing validation tests in adaptive forms


• When to use POST or GET
• Using functions in validation

53
More validation patterns

Example 9.2. A Self-referential, validating form (form2.php)

<!DOCTYPE html PUBLIC


"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=utf-8" />
<title>Validating Name Form</title>
</head>
<body>
<?php
if (isset($_POST['Submit']) && strlen($_POST['namefield'])>0) {
/* if form is submitted and name is not blank, do the following...
*/
?>
<h1>Hello, <?php echo $_POST['namefield']; ?>!</h1>
<p><a href="form2.php">Start again!</a>
<?php
} else {
/* if either the form has not been submitted,
OR, the namefield is blank, display the form...
*/
?>
<form id="textform" name="textform" method="post" action="">
<label>Name:
<input type="text" name="namefield" id="namefield"
value="<?php echo $_POST['namefield']; ?>">
</label>
<?php if (isset($_POST["Submit"])) {
echo "<span style='color:red;'>Please enter your full name!</spa
<input type="submit" name="Submit" id="Submit" value="Submit" />
</form>
<p><a href="form2.php">Start again!</a>
<?php } ?>
</body>
</html>

Notes:

54
More validation patterns

• Test now includes the validation


• This could be function calls to simplify the test
• Responses to the validation occur later...
• strlen() gives the length of a string, 0 if empty
• Note the logical "and" here (&&)
• Messages embedded in form respond to validation errors

Now try this....


1. Add a function to test whether a full name has been entered, and adapt the form to respond
to this test.

2. Add another function to test for a valid email address.

55
56
Chapter 10. Further programming techniques
This chapter will quickly look at a few techniques to make programming a less stressful
experience - it can be difficult to know where to start sometimes when solving problems, so
there are hints on how to read those error messages, and how to discover where the program is
going wrong.To begin with, we'll look at a bit of “code economy” and see how to share common
program statements amongst many pages.

Sharing Common Code across a Website


Sometimes its useful to keep some parts of your program separate from the main PHP and HTML
of your web pages. For example, you might want to develop a set of functions that deal with
one type of data, or that are used in several different pages. To do this, you'll need to use the
include or require functions.

For example:

include("library.inc.php");
require("essentials.inc.php");

The difference between the include() and require() commands is in what happens
if the file cannot be found; with include() the page will continue to be loaded, whereas
with require() the page will fail to load. So in this case the page will complete loading if
library.inc.php is missing, but not if essentials.inc.php does not exist.

It's conventional to distinguish between “proper” PHP pages that produce entire web pages when
executed, and “includes”, which generally contain snippets of code or functions that are shared
between many pages. The included files are generally named with a .inc.php extension, rather
than just .php.

There are also variants which check whether the file has already been included - so
require_once() will only require the file to be included if the file has not already been
included earlier in the program.

Security
Once web pages become interactive, there's often the possibility that the interaction can be abused
by vandals or others with malicious intent. There are certain situations where the security of the
program code must be considered very carefully, to avoid opening up your website to those who
want to abuse it.

57
SQL Injection

SQL Injection

Cross-site Scripting

Clean and Tainted User Input

58

You might also like