Professional Documents
Culture Documents
Practical Internet Programming: Mitxx13
Practical Internet Programming: Mitxx13
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
• Low-level or high-level
• Procedural
• Event-driven
• Object-oriented
• Compiled or interpreted
• Platform-independent or platform-specific
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!).
• 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.
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.
• Disadvantages include the need to compile in advance, greater development time, platform-
dependence.
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.
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.
• 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.
• 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
8
Programming and 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 v. Scripting
• 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).
• Javascript and PHP (in its usual form) are both scripting languages - hurray!
9
Programming and the Web (continued)
• 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.
15
Javascript: What can't it do?
• 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
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?
17
Getting started - Simple dynamic elements
• 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.
18
Getting started - Simple dynamic elements
1. Using the methods getDate(), getMonth() and getFullYear(), write the date
below the time.
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
20
Controlling sequence of instructions
21
Event driven programs
22
Event driven programs
23
24
Chapter 3. Javascript: Variables, Constants and Arrays
• Storing information
• The shape of information
• Storing multiple data items
Storing information
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.
25
Arrays - collections of variables
26
Adding a random element
• 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].
• 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.
1. Get a random floating point number between 0 and 0.99999999999999999 using the
Math.random() method
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
28
Javascript: Controlling the program
• Arithmetic operators ( + - * / ) - for more see the 'JavaScript Arithmetic Operators' section
at http://www.w3schools.com/js/js_operators.asp
• Other methods of the Math object can also be used for rounding numbers, e.g.
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
30
Javascript: Controlling the program
Notes
• The while loop uses a condition in the same way as an if (), but with repetition:
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
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.
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?
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.
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;
?>
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:
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");
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:
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:
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:
37
Creating HTML lists
will sort all the days we have stored in the array into alphabetical order.
<?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.
<?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>";
?>
38
Some Syntax Details
<?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>";
?>
<!-- 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
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>";
}
?>
<?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
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.
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:
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
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;
}
44
Chapter 8. The Interactive Web
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
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.
2. Modify this new function to test whether more than one name (e.g. firstname and surname)
has been entered.
...
<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.
• 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
<?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
?>
<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>
52
More validation patterns
Points to note:
Hint: you could use PHP to write a style="color:red" attribute to the <h1> element.
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.
53
More validation patterns
Notes:
54
More validation patterns
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.
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
58