An Introduction to PHP Scripting, Fasthosts
An Introduction to PHP Scripting, Fasthosts
An
Introduction
to PHP
Scripting
This guide will introduce some simple yet powerful
features of PHP, a popular scripting language, and help
you take your first steps towards building a strong web
presence.
Customer Support | An Introduction to PHP Scripting
Contents
Introduction ......................................................................................... 1
Getting Started .................................................................................... 2
Using a text editor .............................................................................. 2
Creating your page ............................................................................ 2
Using PHP on your page ................................................................... 3
Comments....................................................................................... 3
Displaying text................................................................................. 4
Integrating PHP and HTML ............................................................. 5
Variables .............................................................................................. 7
Example: Creating a variable .......................................................... 8
Arithmetic operators ........................................................................ 9
Data types ..................................................................................... 11
Arrays ............................................................................................... 12
Numerical arrays ........................................................................... 12
Associative arrays ......................................................................... 14
Multidimensional arrays ................................................................ 15
Find the number of entries in an array .......................................... 16
Conditional statements .................................................................... 16
Comparison operators ..................................................................... 17
if() ..................................................................................................... 18
if()… else .......................................................................................... 20
if()… elseif()...................................................................................... 21
Nested if() statements ...................................................................... 23
Loops ................................................................................................. 24
Page 1
Customer Support | An Introduction to PHP Scripting
while()............................................................................................... 24
do… while() ...................................................................................... 25
for()................................................................................................... 26
foreach() ........................................................................................... 27
Functions ........................................................................................... 28
Defining a function ........................................................................... 28
Create a custom function to validate an email address ................ 29
Parameters....................................................................................... 31
Passing variables .......................................................................... 32
Optional parameters ..................................................................... 33
Returning a value from a function .................................................... 34
Completing our example function .................................................... 36
Creating a web form .......................................................................... 39
Using PHP to get user input from a form ......................................... 43
POST or GET................................................................................ 44
Process the form data ................................................................... 45
Securing your forms ......................................................................... 49
Never assume the data retrieved from the form is valid. .............. 49
Never print data directly onto the page ......................................... 50
Never send unprocessed data to a database ............................... 52
Including files .................................................................................... 53
Error handling ................................................................................... 56
Testing your error handler............................................................. 59
Sending an email ............................................................................... 59
Using your new function to send an email .................................... 64
Sending an error report ................................................................. 66
Page 2
Customer Support | An Introduction to PHP Scripting
Page 3
Customer Support | An Introduction to PHP Scripting
Introduction
If you have been following this series of guides from the beginning, you will
already be familiar with HTML. HTML is not a scripting language, it’s a mark-up
language; it simply instructs your web browser what content to display on the
page. You can add text, images, and even the elements required to create a
form. However, HTML alone is only able to display these elements, if you want to
add interactivity to your site, you will need to use a scripting language.
PHP is a popular and extremely flexible scripting language. Because it is free and
open source, it is used by many 3rd party applications such as Wordpress,
Joomla, and Drupal. Even our very own support sites and control panel use PHP
to allow you to search for knowledge base articles, register domain names, add
web hosting and services, update your billing details, and so on.
Page 1
Customer Support | An Introduction to PHP Scripting
Getting Started
Using a text editor
When writing with a scripting language you will need a text editor. While you can
use Notepad, which is supplied with Windows, we highly recommend using an
advanced text editor which includes features designed for developers. One of the
most important features you should look for in your text editor is colour coding
which makes your code much clearer to read, and helps vastly when searching
for errors.
If you already have a preferred text editor please use this, otherwise there are
many text editors available for free under a General Public License (GNU). Two
commonly used text editors are Notepad++ and Crimson Editor. This guide will
assume that you have downloaded NotePad++ from http://notepad-plus-
plus.org/download.
Page 2
Customer Support | An Introduction to PHP Scripting
1 <?php
3 ?>
Comments
When writing any code, particularly PHP code, it is very important to get into the
habit of commenting your code. This will help you better understand how your
code works if you have to modify it at a later date. There are two ways to add
comments in PHP.
Single line comments: These start with two slashes (//). The comment
only applies to the rest of the line; any code on the following line will be run
as normal.
Multiple line comments: These start a slash and then an asterisk (/*).
Unlike the single line comment, everything after the /* will be treated as a
comment, even on the following lines of code. You must close this
comment block with an asterisk and then a slash (*/).
Page 3
Customer Support | An Introduction to PHP Scripting
1 <?php
5 /* This is a multiple
9 ?>
Displaying text
Displaying text on your page with PHP is important when developing web
applications. To do this you can use either of the following commands:
1 <?php
4 ?>
The text you want to display should be written within double or single quotation
marks. The quotation marks tell PHP that everything inside is a string. This will
be explained in the chapter Data types.
Page 4
Customer Support | An Introduction to PHP Scripting
Copy the following code and save it to a file called hello.php. Upload the file to
your FTP server with your chosen FTP client and browse to it in your web
browser. For example, if your web address is http://www.yourdomain.com visit
http://www.yourdomain.com/hello.php.
1 <!DOCTYPE html>
2 <html>
3 <head>
5 </head>
6 <body>
7 <?php
8 // Display a heading
Page 5
Customer Support | An Introduction to PHP Scripting
10 ?>
11 </body>
12 </html>
If your code worked, well done – you are now a web developer, and you’ve just
built your first web application!
If you saw a blank page or received an error, it is possible that there is an error
somewhere in your code. It is worth checking that…
Page 6
Customer Support | An Introduction to PHP Scripting
You have entered a correct opening PHP tag (<?php), and the
corresponding closing (?>) PHP tag.
The text you want to display with the echo command is enclosed in one
opening and one closing single or double quotation mark.
There is a semicolon (;) at the end of each line of PHP code, before the
closing PHP tag.
If you are still receiving an error message, see Error! Reference source not
found. on page Error! Bookmark not defined..
Variables
Variables allow you to hold certain information, which you can then manipulate
within your code. They work on the same principle as algebra, which allows you
to substitute numbers within formulae with letters.
You can simply define a variable in PHP, which can hold any value. Your code
can then refer to that variable to retrieve or modify its value. This allows you to
write code that can perform different tasks depending on the value of one or
more variables.
Variables names always begin with a dollar sign ($). You can give your variables
any name you like, but you can only use letters, numbers (though not the first
character), or underscores (_).
Page 7
Customer Support | An Introduction to PHP Scripting
Please also remember that the name of a variable is case sensitive. This means
you can define a variable called $MyVariable, and one called $myvariable, and
they can both hold different values.
To reduce the risk of confusion when reading your code, it’s a good idea to
decide on a standard naming convention before you start your project. For
example, most PHP developers will only use lower case characters when naming
variables in PHP, with underscores to represent spaces (such as $my_variable).
1 <?php
This example code defines a new variable called "$x” with a numeric value of “1”.
The code then uses the echo command to print the value of $x, followed by
another echo command to print the “<br />” tag. This instructs your web browser
to insert a line break.
The value for the $x variable does not need quotation marks around it, because
we are not using text. Instead we are defining a number that we can then
manipulate.
Finally we add 1 to the value of $x, and again print the value, “2”.
Page 8
Customer Support | An Introduction to PHP Scripting
Wherever possible try to give your variables helpful names that will help you
instantly recognise which data that variable will hold. This will help you no end
when writing, reviewing, or debugging your code.
Arithmetic operators
The following operators allow you to set or modify the value of a variable.
Page 9
Customer Support | An Introduction to PHP Scripting
The following example shows the use of the concatenation character to join
several strings together to form a word.
1 <?php
4 ?>
This example shows the use of several of the arithmetic operators with an
integer.
1 <?php
4 $x = $x - 5; // Subtract 5 to make 5
6 $x = $x / 2; // Divide by 2 to make 25
8 ?>
Page 10
Customer Support | An Introduction to PHP Scripting
Data types
PHP has several data types which you can use when defining a variable. Here
are the most common variable types:
In some programming languages you must specify the type when you define the
variable, but with PHP this is not necessary. Instead PHP will look at the value
you have supplied for the variable and set the appropriate data type for you.
Page 11
Customer Support | An Introduction to PHP Scripting
Arrays
Arrays allow you to assign multiple values to one variable. Each value in the
array has a key, which you can use to retrieve or edit that value. There are three
different types of array, numerical, associative, and multidimensional.
Numerical arrays
To define an array, you can use the following syntax.
1 <?php
3 $var = array("Monday","Tuesday","Wednesday","Thursday",”Friday”);
4 ?>
The above example will create a variable, $var, to represent an array containing
5 string items. Each item can be referred to by its key, which PHP will create
automatically for you. The first item in an array always starts at 0, so the key for
“Monday” is 0, the key for “Tuesday” is 1, the key for “Wednesday” is 3, and so
on.
Because the keys are numbers, this type of array is known as a numeric array.
To retrieve or edit data in an array, just reference the variable name and then the
key within square brackets.
Page 12
Customer Support | An Introduction to PHP Scripting
1 <?php
3 $var = array("Monday","Tuesday","Wednesday","Thursday",”Friday”);
7 ?>
The above example will print “Wednesday” to the page. You can easily edit
existing values by referring to it by its key. If an item with the supplied key doesn’t
exist, it is created allowing you to add extra items to the array.
1 <?php
3 $var = array("Monday","Tuesday","Wednesday","Thursday",”Friday”);
9 $var[5] = “Saturday”;
10 ?>
Page 13
Customer Support | An Introduction to PHP Scripting
Associative arrays
Array keys do not need to be numeric; you can define your own textual keys if
you wish, using the combination “key”=>”value”. These are called associative
arrays.
1 <?php
”thu”=>"Thursday", ”fri”=>”Friday”);
7 ?>
The above example will print “Wednesday” to the page. Alternatively, you can
declare an empty array and then add each item separately.
1 <?php
3 $var = array();
6 $var["mon"] = "Monday";
7 $var["tue"] = "Tuesday";
8 $var["wed"] = "Wednesday";
9 $var["thu"] = "Thursday";
10 $var["fri"] = "Friday";
11 ?>
Page 14
Customer Support | An Introduction to PHP Scripting
Multidimensional arrays
These sound more complicated than they are! A multidimensional array is simply
an array that contains further arrays. For example:
1 <?php
3 $var = array();
6 $menu["appetiser"] = array("Bread",”Olives”,“Breadsticks”);
10 $menu["drinks"] = array("Tea",”Coffee”,“Juice”,”Water”,”Wine”);
11 ?>
Because you have arrays within arrays, to access a value you will need the key
from both, in the format array[key1][key2];
1 <?php
4 ?>
Page 15
Customer Support | An Introduction to PHP Scripting
1 <?php
2 // Define an array
$arr array
6 $items = count($arr);
8 ?>
Conditional statements
Conditional statements in PHP are fundamental to building a web application.
They let you execute particular code depending on certain conditions.
For example, let’s say you have created a web form for your users to contact
you. You will need to process the information your visitor has entered, and send
yourself the relevant email. However, you need to first ensure that you only run
the necessary code when your visitor submits the form, and the data they
entered has been checked to ensure it is valid.
Page 16
Customer Support | An Introduction to PHP Scripting
Comparison operators
A conditional statement will compare two values using an operator. If the
condition is true, the code supplied is executed. You can use the following
operators to compare the values.
Page 17
Customer Support | An Introduction to PHP Scripting
if()
The most common conditional statement is the if() statement. At its most basic it
looks like this:
1 <?php
2 if(condition){
4 }
5 ?>
The if() condition always appears in normal brackets. Following the condition are
the { and } brackets. The code you would like to execute if the condition is met
should be placed within these brackets.
Page 18
Customer Support | An Introduction to PHP Scripting
For example:
1 <?php
5 }
6 ?>
In this example we have used the “==” operator to compare the value of the
variable $x with the number 10. If they are equal, the example then prints the
value to the page.
Page 19
Customer Support | An Introduction to PHP Scripting
if()… else
There might be an occasion where you wish to run one block of code if a
condition is met, and another block of code if that condition is not met. For these
cases the else statement can be introduced to follow an if() statement.
1 <?php
3 if($x == 10){
4 // $x is equal to ten
6 } else {
9 }
10 ?>
As you can see from the example above, the value of $x, which is 15, does not
meet the criteria specified in the if() statement. Therefore, when this code is run it
will display “Condition was not met”.
Page 20
Customer Support | An Introduction to PHP Scripting
if()… elseif()
You can check several conditions at once using the elseif() statement, which
must always follow an if() statement.
1 <?php
3 if($x == 10){
4 // $x is equal to 10
6 } elseif($x == 15){
7 // $x is equal to 15
9 }
10 ?>
In this example, the if() statement checks the value of the $x variable to see if it is
equal to 10. It isn’t, so the code moves on the the elseif() statement which checks
to see if the value is equal to 15. It is, and therefore the second group of code is
executed, printing “Value is 15” to the page.
Page 21
Customer Support | An Introduction to PHP Scripting
You can continue the if() statement with as many elseif() statements as you wish.
1 <?php
3 if($x == 10){
4 // $x is equal to 10
6 } elseif($x == 15){
7 // $x is equal to 15
9 } elseif($x == 20){
10 // $x is equal to 20
12 } else {
15 }
16 ?>
Page 22
Customer Support | An Introduction to PHP Scripting
1 <?php
4 // $x is greater than 10
5 if($x == 15){
6 // $x is 15
8 } else {
11 }
12 } else {
15 }
16 ?>
Page 23
Customer Support | An Introduction to PHP Scripting
Loops
A loop is a block of code that executes several times until its task has been
completed, often with one or more variables that change each time. There are
four different types of loop within PHP.
while()
While loops let you loop through a block of code while a certain condition is true.
1 <?php
3 $num = 1;
11 }
12 ?>
In this example we create a variable called $num with a value of 1. We then run
the code within the while() block as long as the value of $num is equal or less
than 10. The code inside the block prints the current value on the page, and then
increases it by one.
As soon as the value of $num reaches 11, the while() loop will stop running
because the supplied condition is no longer true.
Page 24
Customer Support | An Introduction to PHP Scripting
do… while()
The do… while() loop is very similar to the while() loop. The only difference is that
while() will only execute if the condition is true, but do… while()will always run the
code once, and then repeat if the supplied condition is true.
1 <?php
3 $num = 1;
6 do {
12 ?>
Page 25
Customer Support | An Introduction to PHP Scripting
for()
The for() loop will run a set number of times. When creating the for() loop you
need to enter the following in brackets and separated by semi-colons (;)…
The increment by which the variable will change with each iteration of the
loop.
1 <?php
2 // Loop 5 times
6 }
7 ?>
In this example our for() loop creates a variable called $num, with a starting value
of 1. The code within the for() loop will only run if $num is equal or less than 10,
and on each iteration of the loop the value of $num will increase by 2.
Page 26
Customer Support | An Introduction to PHP Scripting
foreach()
The foreach() loop allows you to cycle through all the values in an array, in the
order in which they appear.
1 <?php
2 // Create an array
6 foreach($food as $item){
8 }
9 ?>
In the foreach() statement you supply name of the variable containing the array
first, then you specify the variable that will be used to represent the current item
in the loop. This must always follow the “as” keyword.
In our example, the value of $item will change on each iteration of the array,
starting with “Pizza” on the first iteration, then “Fish and chips” in the second, and
so on until it reaches the end of the array.
Page 27
Customer Support | An Introduction to PHP Scripting
Functions
A function is a portion of code that can be called independently and performs a
specific task. Often a function is written when code that performs the same job
needs to be run repetitively or accessed from different blocks of code, or even
pages.
PHP has hundreds of built in functions that you can use, or you can create your
own.
Defining a function
Use the following syntax to create a function…
1 <?php
3 // Create an array
4 }
5 ?>
Page 28
Customer Support | An Introduction to PHP Scripting
In your text editor create a new file called validate.php and copy the following
code to it.
1 <?php
3 function validate_email() {
5 }
6 ?>
We have called our function “validate_email”, but you can give it any name you
like.
Page 29
Customer Support | An Introduction to PHP Scripting
1 <?php
3 validate_email();
6 Function validate_email(){
8 }
9 ?>
The opening and closing brackets after the function name are important; they tell
PHP that you are referring to a function. If you try to define or run a function
without brackets, an error will occur.
Page 30
Customer Support | An Introduction to PHP Scripting
Parameters
When you define a function, you can also define parameters that can be passed
into the function. Function parameters are just like variables that are only
available to the code within the function.
In the case of our function, we will need to know the email address that we are
validating, so we will create a parameter called $email.
10 <?php
12 validate_email(“ralph@ralphsdomainname.com”);
13
15 function validate_email($email){
page
17 }
18 ?>
When calling the function we then specify a value for the parameter. When the
code within our function is executed, the variable $email will have the string value
“ralph@ralphsdomainname.com”.
If you copy the above code to your validate.php script and run it, you should see
the email address printed on the page.
Page 31
Customer Support | An Introduction to PHP Scripting
Passing variables
You can also pass variables to functions. For example, we could define a
variable containing our email address and pass that to the validate_email()
function.
1 <?php
3 $address = ralph@ralphsdomainname.com;
4 validate_email($address);
7 function validate_email($email){
page
9 }
10 ?>
Page 32
Customer Support | An Introduction to PHP Scripting
Optional parameters
You can also specify that a parameter is optional, i.e. you can supply it when
calling the function if necessary but you don’t need to. To identify a variable as
optional simply give the variable a default value when you define the function.
1 <?php
3 display_message();
default.”){
the page
8 }
9 ?>
10
When defining your function you should always define optional parameters after
any compulsory parameters. Take this example of a function where an optional
parameter is supplied before a mandatory one.
Page 33
Customer Support | An Introduction to PHP Scripting
1 <?php
4 }
5 ?>
In our example our code will validate the email address. If the email address
appears to be valid our function will return true, otherwise it will return false. The
first step in validating the email address, is to check that something has been
supplied to our $email parameter.
1 <?php
3 $valid = validate_email(”ralph@ralphsdomainname.com”);
6 function validate_email($email){
7 if($email == ””) {
9 Return false;
Page 34
Customer Support | An Introduction to PHP Scripting
10 } else {
12 return true;
13 }
14 }
15 ?>
Our function now contains an if() statement that checks the value of the
parameter $email. If email is a blank string (“”), i.e. nothing has been supplied,
the function returns false, otherwise the function returns true.
When we call the function, we now assign the function to a variable called $valid.
The return value from the function gets assigned to $valid, so the example above
will return true because we are supplying an email address.
If we ran the same function with the following function call, we would receive a
false value from our validate_email() function.
1 <?php
3 $valid = validate_email(””);
4 ?>
Page 35
Customer Support | An Introduction to PHP Scripting
Luckily there is a function within PHP that we can call to check whether our email
address is valid or not. It is called filter_var() and it essentially takes a variable,
and filters it to ensure it is valid.
1 <?php
3 $valid =
filter_var(ralph@ralphsdomainname.com,FILTER_VALIDATE_EMAIL);
4 ?>
This function asks for a string value, and the second parameter supplied states
that we are validating an email address. This built in PHP function returns true if
the email address is in the correct format, and false if not.
We need to add this built in PHP function to our custom function. Because the
filter_var() function returns a value, we can use it in our if()… else statement
directly. We will introduce an elseif() statement.
1 <?php
3 $valid = validate_email(“ralph@ralphsdomainname.com”);
6 function validate_email($email) {
Page 36
Customer Support | An Introduction to PHP Scripting
7 if($email == ““){
9 return false;
12 return false;
13 } else {
15 return true;
16 }
17 }
18 ?>
Now our function checks to ensure a value for $email is supplied, and returns
false if not. If $email is supplied our code moves to the next if()… elseif()
statement, which runs PHP’s built in filter_var() function using our $email
variable. If filter_var() returns false the second condition is met, and we return
false. If filter_var() returns true, our code moves to the else statement and returns
true.
At the moment our example script doesn’t output anything so we can’t see if it’s
working. Let’s add an if() statement when we call our function to display different
text on the page, depending on whether the email address is valid or not.
1 <?php
3 $valid = validate_email(“ralph@ralphsdomainname.com”);
4 if($valid == true){
6 } else {
Page 37
Customer Support | An Introduction to PHP Scripting
8 }
11 function validate_email($email) {
12 if($email == ““){
14 return false;
17 return false;
18 } else {
20 return true;
21 }
22 }
23 ?>
Copy this code to your validate.php file, and upload it. Your script should display
the text “Email address is valid”. Try playing around with the value supplied for
email address, and see what results you get. For example, you could try calling
our validate_email() function with the following values…
1 <?php
8 ?>
Page 38
Customer Support | An Introduction to PHP Scripting
Let’s create a contact form to ask your visitor to enter their email address and a
message. We will validate the data and eventually we will write some code to
send the message via an email to an address you choose. However, for now let’s
just take a look at the basics.
We are going to create a form that will ask for the following information:
The visitors email address, so we can reply to email submitted through the
form.
A subject.
The message.
A submit button, which the user will click in order to send the message.
Page 39
Customer Support | An Introduction to PHP Scripting
In your text editor, create a new page called contact.html. Copy the following
code into it.
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <title>Contact us</title>
5 </head>
6 <body>
10
13
16
18 </form>
19 </body>
20 </html>
Page 40
Customer Support | An Introduction to PHP Scripting
This code on line 7 defines the form. The action attribute instructs your web
browser to load the contact.php page when the form is submitted. We will create
this page shortly.
… …
18 </form>
The method attribute tells your web browser how to submit the form. There are
two options you can set. For the moment enter “post” as the value. We’ll talk a
little more about the method attribute shortly.
We then create the text field that will ask the user to enter their email address.
The input control needs a type attribute which we have set to “text” to specify that
this appears as a text field. We have given it the name “email”, which we will use
to refer to this control in our PHP code later. We have also supplied an id, which
for simplicity we have also called “email”.
The id attribute is used by the label text. When we create our label we add the for
attribute, in which we enter the id of the control we want the label to point
towards.
We’ve also created another text field called “subject” which will ask the user to
enter a subject, and a text area control called “message”. The text area control is
very similar to the text input control, but it allows the user to enter text that spans
multiple lines.
Page 41
Customer Support | An Introduction to PHP Scripting
13
Finally we have added another input control, but we have set the type attribute to
“submit”. This appears in your text browser as a button, and when clicked, will
submit the form. The value attribute sets the text that will be displayed on the
button.
Save the contact.html page and upload it to your web server, then visit it in your
web browser.
Page 42
Customer Support | An Introduction to PHP Scripting
This error is displayed because we have told this form to load contact.php when
submitted, but we haven’t created this file yet.
PHP provides a very easy way to retrieve the information entered into a form – it
assigns the values entered to a variable, called $_POST. The values are added
as an array, which means each field’s value is assigned to the same $_POST
variable. To access them, you would use the following syntax
$_POST[“field_name”]. For example:
1 <?php
3 $email = $_POST[“email”];
4 $subject = $_POST[“subject”];
5 $message = $_POST[“message”];
8 $fail = $_post[“email”];
9 ?>
Page 43
Customer Support | An Introduction to PHP Scripting
POST or GET
When you created your form, you specified that the method to use is “post”. You
can choose to use one of two available methods, POST or GET.
… …
18 </form>
… …
18 </form>
The difference between the two is fairly minor. When submitting a form using
GET, which is the default form method, the contents of the form are submitted as
part of the URL. As an example, our form would submit to the following URL
when using GET:
http://www.yourdomain.com/contact.php?email=email@address.com&subj
ect=Subject&message=Message
If in doubt as to which method to use, you should choose the POST method. With
a POST form the entered information is sent with the page request itself, so there
is no limitation to the amount of data that can be sent.
Page 44
Customer Support | An Introduction to PHP Scripting
The first thing we need to do is check to make sure the form has been submitted.
We can do this easily by establishing if the $_POST variable has been created
for one of our controls. PHP has a built in function called is isset() which we can
use to test if a variable has been set.
1 <?php
3 if(isset($_POST["email"]) == false){
4 // $_POST variable for our "email" control doesn’t exist. The form
5 header("Location: contact.html");
6 } else {
8 }
9 ?>
Page 45
Customer Support | An Introduction to PHP Scripting
You can test to see if this works or not by uploading both your contact.html and
contact.php pages. If you browse directly to your contact.php page, it should
direct you automatically back to contact.html. If you submit the form, you should
see a blank page because we haven’t added any code yet to process the data.
We’ll add that now.
1 <?php
3 if(isset($_POST["email"]) == false){
4 // $_POST variable for our "email" control doesn’t exist. The form
5 header("Location: contact.html");
6 } else {
8 if(validate_email($_POST["email"]) == false) {
11 } elseif($_POST[“subject”] == ""){
12 // No subject entered
14 } elseif($_POST[“message”] == ""){
15 // No message entered
17 } else {
18 // Validation passed
Page 46
Customer Support | An Introduction to PHP Scripting
20 }
21 }
22 ?>
We’ve added an if() statement to validate our email address, and check to ensure
the “subject” and “message” fields hold a value.
However, this code won’t work at the moment. If you submit the form you will
receive the following error message…
We haven’t added our custom validate_email() function yet! You are calling this
function in the first if() statement on line 8, but PHP can’t find this function in your
code. Let’s add it underneath our existing code…
1 <?php
3 if(isset($_POST["email"]) == false){
4 // $_POST variable for our "email" control doesn’t exist. The form
5 header("Location: contact.html");
6 } else {
8 if(validate_email($_POST["email"]) == false) {
11 } elseif($_POST[“subject”] == ""){
12 // No subject entered
14 } elseif($_POST[“message”] == ""){
Page 47
Customer Support | An Introduction to PHP Scripting
15 // No message entered
17 } else {
18 // Validation passed
20 }
21 }
22
24 function validate_email($email) {
25 if($email == “”){
27 return false;
30 return false;
31 } else {
33 return true;
34 }
35 }
36 ?>
Upload your contact.php file to the web server and try out your web form. If you
enter a valid email address and any subject and message, you should see the
message “Validation passed!”.
Page 48
Customer Support | An Introduction to PHP Scripting
Make sure that the data is in a format you are expecting. For example, if you are
asking for a numeric value, there are a number of PHP functions to validate a
number. For information see Error! Reference source not found. on page
Error! Bookmark not defined..
If you are expecting text, make sure you only accept characters that you would
like to allow. If you are validating an address, for example, you probably only
need to accept alphanumeric characters, spaces, and possibly dashes. You don’t
need special characters such as < > ; and * which can be used within malicious
code. A useful built in function to strip all characters from a string, except those
which you allow, is preg_replace().
Page 49
Customer Support | An Introduction to PHP Scripting
preg_replace()
The following example will string all characters that are not alphanumeric (letters
and numbers).
1 <?php
alphanumeric characters
5 ?>
In cross site scripting the JavaScript code can be used to read cookies and steal
data, such as personal information about your visitors or even their passwords if
you use a login
You should never print data directly from an external source onto the page.
Instead there are a number of PHP built in functions that you can use to sanitise
and convert the data into a safe format to display on a page.
Page 50
Customer Support | An Introduction to PHP Scripting
htmlentities()
This function converts a given string into a harmless string containing HTML
entities. For example, the tag “<script>” which tells your web browser that the text
that follows is JavaScript, would become “<script>”. Because the function
has converted the < and > brackets into html entities, your web browser will not
treat it as an HTML tag and will not execute any JavaScript code. The string
when displayed on the page, however, will appear as normal.
For example, try copying this code into a PHP file, uploading it to your server,
and then visiting the page in your web browser. You should see a page that
contains the string "<script>alert('This is a JavaScript alert');</script>".
1 <?php
4 echo htmlentities($x);
5 ?>
Now try removing the htmlentities() function, and printing the $x variable directly
to the page. You will notice that, instead of printing the string on the page, a
JavaScript alert box pops up.
Hopefully this demonstrates how important this function can be. If you accept
data from a web form, and print it directly to the page without htmlentities(), it
would be easy for a malicious user to submit their own JavaScript code in your
web form. If they can do this, they can perform a number of activities, such as
hijacking user’s cookie or session data to steal personal information, or infecting
your website with a virus.
Page 51
Customer Support | An Introduction to PHP Scripting
strip_tags()
This function does exactly what the name suggests; it strips any HTML tags from
a given string.
1 <?php
4 echo strip_tags($x);
5 ?>
This example will remove the “<script>” and closing “</script>” tags from the
string. Without these tags, the JavaScript code will not run.
If the data entered into the form is not sanitised before it is sent to the database,
a malicious user could inject their own SQL code.
This could allow them, in theory, to modify, add, or even delete the data in your
database.
Page 52
Customer Support | An Introduction to PHP Scripting
Including files
Another extremely useful feature of PHP is the ability to include additional files
into your code. Let’s say you have written a function that you need to run on
more than one page of your website. Rather than copying the code for each
page, you can instead create another PHP file and place your function into that.
You can then call that file within each page that needs to access your function.
For example, on our website we might want to ask users to enter their email
address to sign up for a newsletter. When they sign up we will need to validate
their email address to make sure it’s valid. We’ve already written a function to do
this, which is used by our contact form. There is no need to write that function
again, we could just move that function into a separate file that both the contact
form and the newsletter sign up form could access.
Using your text editor, create a new file called include.php. Copy the
validate_email() function we wrote earlier to it, and upload it to the same folder as
your contact.html and contact.php files.
1 <?php
3 function validate_email($email) {
4 if($email == "") {
6 return false;
Page 53
Customer Support | An Introduction to PHP Scripting
9 return false;
10 } else {
12 return true;
13 }
14 }
15 ?>
PHP will not allow two functions to be defined with the same name, so open up
your contact.php file in your web browser and delete the validate_email()
function code.
Now let’s include our new file. Add the following line to the top of your
contact.php file.
3 include "include.php”;
1 <?php
3 include "include.php";
6 if(isset($_POST["email"]) == false) {
8 header(’Location: contact.html’)
Page 54
Customer Support | An Introduction to PHP Scripting
9 } else {
11 if(validate_email($_POST["email”]) == false) {
14 } elseif($_POST["subject”] == ""){
15 // No subject entered
17 } elseif($_POST["message”] == ""){
18 // No message entered
20 } else {
21 // validation passed
23 }
24 }
25 ?>
Save the file, upload it to your web server, and try it out. If you get any error
messages check to ensure that the file you are calling in your include call is spelt
correctly, and that the contact.php and include.php files have been uploaded to
the same folder on your web server.
Page 55
Customer Support | An Introduction to PHP Scripting
Error handling
It is important that you trap any errors that occur in your code, to allow you to
track down and resolve the cause. Bugs often creep in to web applications,
particularly larger ones, but if you have a robust error handling process, trapping
and fixing them shouldn’t be difficult.
PHP allows you to create your own error handling function, which will be called
whenever an error occurs. You could use this function to send a report of the
error by email, and/or to log the error to a text file, as well as displaying the error
on the screen.
1 <?php
3 set_error_handler("error_handler");
Page 56
Customer Support | An Introduction to PHP Scripting
6 function error_handler($err_number,$err_text,$err_file,$err_line){
8 }
9 ?>
In this example we set the error handler to a custom function that we’ve called
“error_handler”.
The custom error handling function can accept four parameters, which we’ve
called $err_number, $err_text, $err_file, and $err_line.
$err_number – Each error in PHP has a unique code. The first parameter
will contain this code for the error that’s just occurred.
$err_text – The second parameter contains the text of the error message.
$err_file – The third parameter contains the name of the file in which the
error occurred. This is extremely useful for tracking the code that caused
the error.
$err_line – The fourth parameter tells you on which line of your code the
error was encountered. Again, this is essential for tracking down the cause
of the error.
Page 57
Customer Support | An Introduction to PHP Scripting
1 <?php
3 set_error_handler("error_handler");
6 function error_handler($err_number,$err_text,$err_file,$err_line){
12 }
13 ?>
Page 58
Customer Support | An Introduction to PHP Scripting
1 <?php
2 // Trigger an error
4 ?>
Sending an email
Let’s create a function to send an email. The built in PHP function mail() can be
used to send the mail, but before we do we need to apply a little validation.
Our function will have three parameters, $from, $subject, and $message. When
calling the function we will supply the email address we are sending the mail
from, the subject of the email, and the message itself. We will validate the
supplied email address, check that a subject and message have been supplied,
and send the mail.
Open the include.php file in your text editor, and add the following code below
the validate_email() function, but before the closing PHP ?> tag.
3 if(validate_email($from) == false) {
5 return false;
Page 59
Customer Support | An Introduction to PHP Scripting
6 } elseif($subject == "") {
7 // No subject supplied
8 return false;
9 } elseif($message == "") {
10 // No message supplied
11 Return false;
12 } else {
13 // Send email
14 }
15 }
As you can see we are defining a function called “send_email” with our three
parameters. The if() statement validates each parameter in turn and returns false
if any of those parameters are invalid or not supplied.
Now we’ll create the code to prepare and send the email if the validation passes
successfully.
The mail() function needs to know what time zone to use when sending the
email, so we’ll set this first. While your server may have the time zone set by
default, it’s best to set this manually to be safe especially if you are hosting your
website on a shared web server.
We will use the PHP built in function date_default_timezone_set() to set the time
zone to “Europe/London”.
13 // Set timezone
14 date_default_timezone_set ("Europe/London");
Next we need to set the email address from which the email will be sent. This
must be a valid email address.
Page 60
Customer Support | An Introduction to PHP Scripting
17 $to = "ralph@ralphsdomainname.com";
We now need to prepare our email address to send from the email address
supplied to the function, which will eventually be the email address your visitor
provides when filling out the contact form. We set the email address in the email
headers, so we’ll create another variable called $headers for these.
The “\r\n” characters specify a line break should be used. Because email headers
are plain text, and not HTML, the “<br />” tag will not create a line break here.
With our headers prepared, we can send the email. Before we do this, however,
we need to use another PHP function called ini_set() to set the sender email
address configuration setting for your website. This is necessary if sending mail
from Fasthosts web servers.
Page 61
Customer Support | An Introduction to PHP Scripting
Following the ini_set() function is the mail() function. We supply the following
variables as parameters.
$to – The email address we are sending to, which we have just set.
“-f” . $from – Fasthosts web hosting require you to again supply the
senders email address, along with the “-f” flag. If you are not hosting your
site with Fasthosts, you may not need this additional parameter.
24 ini_set("sendmail_from", $from);
The mail() function returns true if the email was accepted for delivery, and false if
not. Our function will return the value that the mail() function supplies.
That’s all there is to it! Your complete send_email() function should look like
this…
Page 62
Customer Support | An Introduction to PHP Scripting
3 if(validate_email($from) == false) {
5 return false;
6 } elseif($subject == “”){
7 // No subject supplied
8 return false;
9 } elseif($message == “”){
10 // No message supplied
11 return false;
12 } else {
13 // Set timezone
14 date_default_timezone_set(“Europe/London”);
15
17 $to = “ralph@ralphsdomainname.com”;
18
22
24 ini_set(“sendmail_from”,$from);
26 }
27 }
Page 63
Customer Support | An Introduction to PHP Scripting
Because our send_email() function returns true if successful, and false if not, we
are going to call the function inside another if() conditional statement. This will
allow us to display an error if we can’t send the email and a success message if
we can.
This is the code we will add after the validation. It calls our send_email() function
with the values retrieved from the form input controls called “email”, “subject”,
and “message”.
1 // Validation passed
3 // Message sent
5 } else {
7 echo ” An error occurred whilst sending the email, please try again
later”;
8 }
Page 64
Customer Support | An Introduction to PHP Scripting
Open the contact.php file in your text editor, and add the code above to it as
shown below.
1 <?php
3 include “include.php”;
6 if(isset($_POST["email"]) == false) {
8 header('Location: contact.html');
9 } else {
11 if(validate_email($_POST["email"]) == false) {
14 } elseif($_POST["subject"] == "") {
15 // No subject entered
17 } elseif($_POST["message"] == "") {
18 // No message entered
20 } else {
21 // Validation passed
22 if(send_email($_POST["email"], $_POST["subject"],
$_POST["message"])) {
23 // Message sent
25 } else {
Page 65
Customer Support | An Introduction to PHP Scripting
28 }
29 }
30 }
31 ?>
Upload the contact.php file to your web server, along with the include.php file,
and test it. Did you receive the email? If you didn’t make sure both the email
addresses you are sending to and from exist, and that one of them is hosted with
your web hosting provider.
$report);
19 if($success == true) {
Page 66
Customer Support | An Introduction to PHP Scripting
/>";
21 }
This code compiles the report to send, using the $report variable. We then call
our send_email() function, specifying that we are sending the email from
“error@ralphsdomainname.com”, with a subject of “Error report”.
As a courtesy we inform the user that an error report has been sent to the
website administrator if the email is sent successfully.
Let’s put this code into our error handling function. Open the include.php file in
your text editor and add the above code to your error_handler() function.
1 <?php
3 set_error_handler("error_handler");
Page 67
Customer Support | An Introduction to PHP Scripting
12
18 $success = send_mail("error@ralphsdomainname.com","Error
report",$report);
19 if($success == true) {
administrator.<br />";
21 }
22 }
23 ?>
Make sure you trigger the error after you have included your include.php file,
because that’s where you define your custom error handler.
1 <?php
3 include "include.php";
5 // Trigger an error
Page 68
Customer Support | An Introduction to PHP Scripting
Save both your contact.php and include.php files, upload them to your web
server, and test your form. Don’t forget to remove the trigger_error() function call
once you’ve finished testing your error handler.
Connecting to a database
One of the most powerful features of PHP is the ability to connect to a database.
You can use a database to significantly extend the capabilities of your website.
For example, a database makes it rather simple to add or modify website content
through a content management system, without the need to modify your site’s
source files. You could also implement search features, an account sign up and
login system, or a shopping basket.
The database of choice for PHP users is MySQL which, just like PHP, is free and
open source software. It is also extremely powerful, and as a result is one of the
most popular database solutions available today.
An introduction to SQL
SQL is an acronym for Structured Query Language. It is a programming
language specifically designed for querying and managing the data held within a
relational database.
With PHP, you simply connect to the MySQL database and send an SQL query
to the database server. The MySQL server will then process the query, and send
the requested data back for PHP to handle.
SQL queries can be very basic. One of the most common types of query is a
SELECT query, which simply returns data from the database. For example, the
following query will display all records found in a table called “Products”.
Page 69
Customer Support | An Introduction to PHP Scripting
The asterisk (*) is a shorthand method of telling MySQL to select all fields in the
table. If you only needed to retrieve the value of two fields called “ID” and “Name”
you could use.
The database host – This is the address you use to connect to the
database. If the database is hosted on the same server as your website this
will be “localhost”, otherwise it will probably be an IP address.
The database name – This is the name you chose when you created the
database.
The database user – The username you use to connect to the database.
The script that we will write will retrieve a list of products from a table called
“Products” in your database. If this table does not exist, you can either create it,
Page 70
Customer Support | An Introduction to PHP Scripting
with the following fields, or just substitute the table and field names for your own
in the code.
Page 71
Customer Support | An Introduction to PHP Scripting
First, we will define the database connection details. We do this using a feature
of PHP called constants. Constants are similar to variables, except that their
value cannot be changed during runtime.
1 <?php
2 define("CONSTANT_NAME", "Value");
3 echo CONSTANT_NAME;
4 ?>
When defining the constant, you can use any name you wish. However,
developers usually use upper case names for constants to help them easily
identify them in their code.
Note that when defining a constant it is named within a string, but when referring
to it from then on no quotation marks are required.
Page 72
Customer Support | An Introduction to PHP Scripting
Let’s define four constants that will hold our database connection details.
1 <?php
6 ?>
Next, we’ll prepare the SQL query that we will be using. It’s good practice to only
open the connection to the database for the minimum time necessary to run the
query and return the results, so we’ll prepare the query before we open the
connection.
All our query will do is return the ID, name, and a description of each product in
our “Products” table. The SQL query will look like this.
Page 73
Customer Support | An Introduction to PHP Scripting
This query will select the fields “ID”, “Name”, and “Description” from the table
called “Products”. It will also order the results in ascending order by the “Name”
field. This will result in all products being listed in alphabetical order.
1 <?php
8 $query = "SELECT ID, Name, Description FROM Products ORDER BY Name ASC;";
9 ?>
This code creates a new variable called “mysqli” (you can use any name you
like), which contains the database connection. When we initialise the connection
we are creating a new object based on the MySQLi extension.
Page 74
Customer Support | An Introduction to PHP Scripting
to the $mysqli variable contains several functions that we can use to query the
database and retrieve the results.
When creating the database object we specify the database host, user,
password, and database name. These parameters must be placed in this order.
At the moment we have no idea if the connection to the database has been
successful. So let’s find out.
14 if(mysqli_connect_errno()) {
>connect_error();
17 } else {
20
22 $mysqli->close();
23 }
After this the command $mysqli->close() closes the connection to the database.
Page 75
Customer Support | An Introduction to PHP Scripting
In this code we run two functions in the MySQLi object, connect_error() and
close(). Notice how to run these functions you must specify the name of the
variable containing the object, followed by a dash and greater than symbol (->),
then the function name.
The full code in your database.php file should look similar to this…
13 <?php
database.
18
ASC;";
21
24
26 if(mysqli_connect_errno()) {
Page 76
Customer Support | An Introduction to PHP Scripting
>connect_error();
29 } else {
32
34 $mysqli->close();
35 }
36 ?>
Save the database.php file and upload it to your web server, it’s time to test it.
Page 77
Customer Support | An Introduction to PHP Scripting
Connection Errors
If it worked and you’re now looking at a page with the words “Connection
successful” then well done! If it didn’t work, then there is a good chance you’re
looking at one of these errors (or one very similar).
Cause Solution
This is a simple “Access denied” error. Check that your username and
The username and/or the password password are spelt correctly.
you are using are not correct. Remember they are case sensitive. If
your database is hosted with
Fasthosts you can change the
password in your control panel.
Warning: mysqli::mysqli() [mysqli.mysqli]: (HY000/2003): Can't connect to
MySQL server on '<database host>' (10061)
Cause Solution
The database host you supplied is Check that the database host is
incorrect or the database server is correct. If your database is hosted with
unavailable. Fasthosts this will be an IP address,
which is available in your control
panel.
Running a query and retrieving results
All we’ve done so far is successfully connect to the database; we have yet to
query and data from it.
Page 78
Customer Support | An Introduction to PHP Scripting
In our current example this isn’t a risk, because we are not using data from an
external source (such as a form) to create our SQL statement. However, it’s good
practice to get into the habit of using prepared statements.
19 $stmt = $mysqli->stmt_init();
20 if(!$stmt->prepare($query)) {
23 } else {
24 //Statement created
26
27 //Close statement
28 $stmt->close();
29 }
The first line of code uses the MySQLi objects stmt_init() function to initiate the
prepared statement engine. This creates another object, which we’ve assigned to
a variable called $stmt. This object will allow us to prepare and run the statement,
and retrieve the results.
The following line then prepares the statement using the query we defined
earlier, in the $query variable. If there is a problem preparing the query, we
display the error message.
Page 79
Customer Support | An Introduction to PHP Scripting
If the query is prepared successfully you must remember to close the statement
when you have finished using it, just like you must close the database
connection.
25 $stmt = $mysqli->stmt_init();
26 if(!$stmt->prepare($query)) {
These lines of code are relatively easy to understand. The first, $stmt->execute(),
simply executes our SQL query.
The second, $stmt->store_result(), stores the results from the database which
will allow our following code to access those results. Let’s check to see if there
were any records returned.
29 if($stmt->num_rows == 0) {
32 } else {
35 }
Page 80
Customer Support | An Introduction to PHP Scripting
The property “num_rows” of our statement contains the number of records that
were retrieved from the database. If this is 0, our code displays a message to
inform the user that there were no records; otherwise it displays the number of
records found.
With prepared statements we need to create a new variable for each field that we
have asked for in our query. Let’s take another look at the SQL we are using:
We are asking for the values of the ID, Name, and Description fields. We must
bind, or link, each of these three fields to its own variable.
It doesn’t matter what you call these variables. However, to make it easy to
understand which variable contains data from which field, we’ll call them $id,
$name, and $description.
The bind_result() function connects the fields in our query with the variables. It is
important that your variables appear in the same order when passed to the
bind_result() function as they do in your SQL statement.
Page 81
Customer Support | An Introduction to PHP Scripting
40 while($stmt->fetch()) {
41 echo $name . " (ID: " . $id . ") - " . $description . "<br />";
42 }
The prepared statement’s fetch() function will retrieve the values from the first
record returned, and then each time it is called it will return the next record until it
reaches the last. When there are no results left, the function will return false.
Our while() loop will loop until fetch() returns false, i.e. it will loop once for each
record returned from our results.
Each time the fetch() function is called it will assign the data for each field in the
current record to the corresponding variable that we bound earlier. Hence, for
each iteration of the loop our $id, $name, and $description variables will contain
the relevant details from the current record, which we can print on the page.
Page 82
Customer Support | An Introduction to PHP Scripting
1 <?php
database.
ASC;";
12
14 if(mysqli_connect_errno()) {
>connect_error();
17 } else {
19 $stmt = $mysqli->stmt_init();
20 if(!$stmt->prepare($query)) {
Page 83
Customer Support | An Introduction to PHP Scripting
23 } else {
25 $stmt->execute();
26 $stmt->store_result();
27
29 if($stmt->num_rows == 0) {
30 // No records found
32 } else {
/>";
35
38
40 while($stmt->fetch()) {
42 }
43 }
44
45 // Close statement
46 $stmt->close();
47 }
48
50 $mysqli->close();
51 }
52 ?>
Page 84
Customer Support | An Introduction to PHP Scripting
If you would like to learn more about setting up and querying MySQL databases,
as well as building a powerful web application using a database, then take a look
at our next guide in this series An Introduction to MySQL Databases.
Cause Solution
This error message is displayed when Check that the URL you are browsing
you browse to a PHP file that doesn’t to exists on your web server. If you are
exist. hosting your website on a Linux web
server, remember that file names are
case sensitive, so a file called
“index.php” would not be found if you
browsed to “Index.php”.
Parse error: syntax error, unexpected <statement>, expecting ',' or ';'
Cause Solution
This error message is most often Check the line before the line number
caused by a missing semi-colon at the given in the error message to make
end of the line. sure there is a semi-colon (;) at the
end of the text.
Page 85
Customer Support | An Introduction to PHP Scripting
Cause Solution
This error message is often caused by Check that each if() conditional
an unclosed if() condition, loop, or statement and loop (while(), do…
string. while(), for(), foreach()) has the correct
number of opening and closing { }
brackets. Check also that every string
you define has an opening and closing
single or double quotation mark.
Missing argument <n> for <function>()
Cause Solution
You have defined a function, The error message will tell you on
<function>, which requires one or which line your function is called.
more parameters to be supplied when Check the code on that line to make
the function is called. However, your sure you are supplying the correct
code is missing one or more number of parameters.
parameters (<n>).
Parse error: syntax error, unexpected '='
Cause Solution
You are defining a variable but have The error will give you the line number
not used the dollar ($) sign when on which the error occurs. Check that
naming it. For example “x = 5;” instead line in your code to make sure you are
of “$x = 5;”. defining the variable correctly.
Notice: Use of undefined constant <name> - assumed '<name>'
Cause Solution
You are most likely referring to a The error will give you the line number
variable incorrectly. For example, you on which the error occurs. Make sure
have defined a variable called $x in you are referring to your variable
your code, but are referring to it as “x”. correctly.
Page 86
Customer Support | An Introduction to PHP Scripting
Cause Solution
You are calling a function, Check the spelling of the function you
<function>(), which does not exist. are calling. If the spelling is correct,
make sure the file in which the function
exists has been included in your
project.
Camel case Camel case is where names with multiple words are written
as one word without spaces, with capital letters to separate
the words. This is common when naming functions, for
example myFunctionName().
Client side Something that is described as client side is executed on the
user's machine. JavaScript, for example, is a client side
language because it is run by the web browser after the
page has downloaded.
Concatenation The concatenation operator is a full stop (.) and allows two
Operator values to be joined together.
Page 87
Customer Support | An Introduction to PHP Scripting
Page 88
Customer Support | An Introduction to PHP Scripting
Page 89
Customer Support | An Introduction to PHP Scripting
Variable functions
Function Name Description
filter_var() Filter a variable to see if it appears valid.
is_array() Check to see if a given variable is an array.
is_bool() Check to see if a given variable is a Boolean (true or false)
data type.
is_int() Check to see if a given variable is an integer (whole
number) data type.
is_null() Check to see if a given variable is null, i.e. has no value.
is_numeric() Check to see if a given variable is a number. Unlike
is_int(), the number doesn’t necessarily have to be an
integer.
is_string() Check to see if a given variable is a string data type.
isset() Check to see if a given variable has been initialized.
unset() Destroy a variable.
String functions
Function Name Description
addslashes() Returns a string with backslashes before characters
that need to be escaped for database queries (e.g.
single/double quotes and backslash characters).
echo() Print text to the page. This function is the same as
print().
html_entity_decode() The opposite of htmlentities(), converts a string
containing HTML entities to normal characters.
htmlentities() Convert a string to HTML entities. This is a useful
security measure, and should be used whenever
printing data from an external source to the page.
ltrim() Trim whitespace (e.g. spaces, tabs, line breaks) from
the left side of a string.
Page 90
Customer Support | An Introduction to PHP Scripting
Error functions
Function Name Description
set_error_handler() Set the error handler to a custom function. This gives you
much more control over how your application deals with
errors.
trigger_error() Triggers a custom error.
Page 91
Customer Support | An Introduction to PHP Scripting
contact.html
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <title>Contact us</title>
5 </head>
6 <body>
10
13
16
18 </form>
19 </body>
20 </html>
Page 92
Customer Support | An Introduction to PHP Scripting
contact.php
1 <?php
3 include "include.php";
6 if(isset($_POST["email"]) == false) {
8 header('Location: contact.html');
9 } else {
11 if(validate_email($_POST["email"]) == false) {
14 } elseif($_POST["subject"] == "") {
15 // No subject entered
17 } elseif($_POST["message"] == "") {
18 // No message entered
20 } else {
21 // Validation passed
22 if(send_email($_POST["email"], $_POST["subject"],
$_POST["message"])) {
23 // Message sent
25 } else {
Page 93
Customer Support | An Introduction to PHP Scripting
28 }
29 }
30 }
31 ?>
include.php
1 <?php
3 set_error_handler("error_handler");
6 function error_handler($err_number,$err_text,$err_file,$err_line) {
12
report", $report);
19 if($success == true) {
administrator.<br />";
Page 94
Customer Support | An Introduction to PHP Scripting
21 }
22 }
23
25 function validate_email($email) {
26 if($email == "") {
28 return false;
31 return false;
32 } else {
34 return true;
35 }
36 }
37
40 if(validate_email($from) == false) {
42 return false;
43 } elseif($subject == "") {
44 // No subject supplied
45 return false;
46 } elseif($message == "") {
47 // No message supplied
48 return false;
49 } else {
50 // Set timezone
51 date_default_timezone_set("Europe/London");
52
Page 95
Customer Support | An Introduction to PHP Scripting
54 $to = "ralph@ralphsdomainname.com";
55
59
61 ini_set("sendmail_from", $from);
63 }
64 }
65 ?>
Page 96