Server-Side Scripting With PHP4
Server-Side Scripting With PHP4
2 Introduction 3
2.1 What is server-side scripting . . . . . . . . . . . . . . . . . . . . . 3
2.1.1 Standard static web pages . . . . . . . . . . . . . . . . . . 3
2.1.2 Web pages generated with server side scripting . . . . . . 4
2.2 When to use server-side scripting . . . . . . . . . . . . . . . . . . 5
2.3 What you need to get started . . . . . . . . . . . . . . . . . . . . 5
3 Installation 6
3.1 Linux server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.1.1 Selecting a Linux distribution . . . . . . . . . . . . . . . . 6
3.1.2 Installing Linux . . . . . . . . . . . . . . . . . . . . . . . . 7
3.1.3 Installing packages after Linux installation . . . . . . . . . 7
3.1.4 Testing the web server . . . . . . . . . . . . . . . . . . . . 7
3.1.5 Test the PHP installation . . . . . . . . . . . . . . . . . . 8
3.1.6 Test the MySQL installation . . . . . . . . . . . . . . . . 8
3.2 Windows 2000 server . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.2.1 Installing MySQL in Windows 2000 . . . . . . . . . . . . 9
3.2.2 Installing PHP in Windows 2000 . . . . . . . . . . . . . . 9
3.2.3 Using Microsoft Access databases with PHP . . . . . . . . 10
1
6 Interfacing databases 20
6.1 Structured Query Language SQL . . . . . . . . . . . . . . . . . . 20
6.1.1 SELECT command . . . . . . . . . . . . . . . . . . . . . . 20
6.1.2 INSERT command . . . . . . . . . . . . . . . . . . . . . . 22
6.1.3 UPDATE command . . . . . . . . . . . . . . . . . . . . . 22
6.2 Scenario: MySQL database . . . . . . . . . . . . . . . . . . . . . 22
6.2.1 Creating a database and a database user . . . . . . . . . . 23
6.2.2 Extracting information from the database with PHP . . . 25
6.2.3 Creating new records with PHP . . . . . . . . . . . . . . 26
6.2.4 Updating records with PHP . . . . . . . . . . . . . . . . . 27
6.2.5 Finishing the application . . . . . . . . . . . . . . . . . . 29
6.3 Scenario: Access database on Microsoft Windows 2000 Server . . 30
6.3.1 Extracting information from the Microsoft Access database
with PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
6.3.2 Creating new records with PHP . . . . . . . . . . . . . . 32
6.3.3 Updating records with PHP . . . . . . . . . . . . . . . . . 33
6.3.4 Finishing the application . . . . . . . . . . . . . . . . . . 35
2
1 Preface
1.1 What is PHP?
PHP (originally Personal Home Page) is a programming language used to
enhance web pages. It is a server-side scripting language meaning, that it is exe-
cuted on the server as apposed to client-side scripting languages like Javascript.
PHP is also an embedded scripting language. This means that you can de-
sign your web pages as usual and embed the programming language where it is
needed. PHP is very often used to extract dynamic web content from a database.
1.3 Prerequisites
It is assumed that the reader has some prior experience with web design and
some basic understanding of HTML. Experience with WYSIWYG1 HTML ed-
itors is generally not enough, since you have to wite a lot of HTML by hand
when doing server-side scripting. For an introduction to HTML refer to A short
introduction to HTML and CSS [2].
2 Introduction
In this section we will focus on the basic principles of server-side scripting. In
what ways does server-side scripting differ from standard static web pages?
3
Figure 1: Communication model for static web pages.
Figure 2: Communication model for dynamic web pages generated with server-
side scripting.
2 A URL can also refer to a compiled program. In that case you would not call it server-side
scripting (since it is not a script), but the communication model would still be the same.
4
figure 2 the scripting engine is often in contact with several resources. This con-
nection to databases or external hardware is what makes server-side scripting
so attractive. The scripting engine can make decisions based on databases or
other resources and generate web pages that change dynamically. The scripting
engine can also make decisions based on user input, making it possible to create
web sites that are more interactive.
5
4. You also need some sort of text editor. Almost any text editor will do, we
recommend a text editor like Emacs [3] or Ultra Edit [4]. It is important
to get comfortable with your text editor. You will be spending a lot of
time with it. You could also use whatever HTML editor you are using
at the moment, but some of them get confused (and report errors) when
you start putting PHP (or any other scripting language) in your HTML
documents.
3 Installation
Your installation scenario depends on your operating system. Here we will go
through some of the considerations for two different scenarios:
1. A Linux operating system running Apache web server, MySQL and PHP.
2. A Windows 2000 operating system running Internet Information Server
(IIS), MySQL/Access database and PHP.
6
If you have no idea which to choose, we recommend you download RedHat or
Mandrake from their web sites and burn installation CD-ROMs. The installation
CD-ROMs are usually bootable, meaning you can insert them in the CD-ROM
drive and reboot the computer to start installation.
7
/home/your_user_name/public_html
If this directory does not exist in your home directory you should create it with
the command:
mkdir /home/your_user_name/public_html
Try placing an HTML file in that directory and type the the following address
in your browser:
http://server_name/~your_username/name_of_file.html
You should see the HTML document displayed in the browser.
<body>
<?phpinfo() ?>
</body>
</html>
Type the address of the new document in your browser and you should see a
PHP info page.
mysql>
You could try issuing a command like:
mysql> SHOW DATABASES;
This should print a list of the available databases.
8
3.2 Windows 2000 server
This guide is based on a Windows 2000 Server running Internet Information Ser-
vices (IIS), which is the default web server. If you are using another web server
than IIS in a Windows 2000 Server, the installation might work automatically,
but after the installation has finished you can otherwise refer to install.txt
and readme.txt in C:\php for information about integrating PHP with your
server.
If you would like to use MySQL as your database server, MySQL should be
installed first. For installation of MySQL please read section 3.2.1. If you are
not interested in using MySQL, you can go straight to the installation of PHP
in section 3.2.2.
9
the SMTP server, you can fill it in if you know it or just leave as it is. Also leave
the selection of Microsoft IIS 4 or higher. When asked for the IIS Scriptmap
Node Selection mark all topics, if you want to run PHP on all web servers.
After the installation it is recommended, that the I_USR is granted read and
execute rights to php.exe and php4ts.dll, and list folder content, read
and write rights to the sub folders of c:\php.
Testing the PHP server is done as in section 3.1.5.
10
4.2 The Form
The form is very straight forward. Open your text editor and type in the fol-
lowing.
<html>
<head>
<title>Simple Test Application</title>
</head>
<body>
<h1>Simple Test Application</h1>
<form action="do_form.php" method="post">
</form>
</body>
</html>
Save the file with the extension *.html or *.htm. The form should look like
figure 3.
11
4.3 The PHP script
The next thing we need is a script for interpreting the information entered in the
form. Enter the following in your text editor and save the file as do_form.php.
The action property of the form tag in the HTML file above states that the
information from the form should be sent to a file called do_form.php.
<html>
<head>
<title>Simple Test Response</title>
</head>
<body>
<h1>Response from server</h1>
<?php
echo "Your email address is: <b>$email</b> <br> \n";
list ($mailbox, $server) = split ("@",$email,2);
echo "Your email must be located at the server <b>$server</b>.<br> \n";
echo "And your mailbox is called: <b>$mailbox</b> <br> \n";
?>
</body>
</html>
This first example application illustrates one of the ways PHP can be used to
make you web pages interactive. You should not worry if you dont understand
12
every single line of code in the example. The important points to note in the
example are:
Forms can be used to send information to scripts. The action property
of the form tag indicates where the information should be sent.
PHP scripts are text files that look much like HTML, but a special tag
<?php ?> escapes the HTML mode and allows the developer to write code
in the PHP scripting language.
The PHP scripting language has commands for processing input from
forms and writing output to the users browser.
<head>
<title>How to escape HTML mode</title>
</head>
</body>
<h1>How to escape HTML mode</h1>
<?php
echo "We are now in PHP mode<br>\n";
?>
</body>
</html>
There are several other ways of escaping HTML (listed below) but I recommend
the approach illustrated above.
13
<?php echo("Use this approach\n"); ?>
<script language="php">
echo ("For editors like FrontPage");
</script>
echo "This, on
the other
hand, is only
one instruction";
?>
5.1.3 Comments
Comments can (and should be) placed in the PHP code using one of the following
notations.
/* Multi
Line
Comment */
We recommend that you adapt one of the styles and stick with it to avoid any
confusion.
14
Variable names must begin with a letter or the underscore character. Variable
names are case-sensitive. The following lines illustrate valid variable names:
$firstname = "Michael";
$firstName = "John";
$first_name = "Peter";
$age = 23;
A variable is defined when a value is assigned to it. Variables are valid within the
context in which they are defined (variable scope). This usually means within
the entire PHP script. The variables are however not automatically valid within
functions (refer to section 5.4). Variables within functions are only defined in
the functions (local variables) and global variables needed in the functions must
be explicitly declared with the global keyword.
15
shape => round,
name => apple);
?>
PHP does not support explicit type declaration. The type of a variable depends
on the context in which it is evaluated. If you try to output a variable (e.g.
with echo) it is evaluated as a string. If you try to add an integer to it, it is
evaluated as an integer and so on. This makes it a little easier to get started
with the language, because you dont need to worry about data types. On the
other hand it is left up to the programmer to keep track of data types. This can
cause unpredicted behavior if you are not careful.
16
<html>
<head>
<title>Processing script</title>
</head>
<body>
<h1>Output</h1>
<?php
echo "Last name: ";
echo $last . "<br>";
?>
</body>
</html>
This little example illustrates the most important features for passing informa-
tion from forms to scripts (but also a few general features). You should notice
the following:
Variables with the same names as the names of the input boxes are auto-
matically generated for you. When you have an input box named first in
your HTML document, the contents of this input box will be available to
you in a variable named $first in the PHP script receiving the content
of the form.
Information can be written in web pages using the echo function (print
would have the same effect).
Strings are indicated by quotation marks.
Strings are concatenated (glued together) with the . operator.
Variable names within double quotation marks are evaluated before print-
ing the string. Had we used single quotation marks the variable name
would have been printed instead of the value (try replacing the double
quotation marks with single quotation marks).
You will be using string manipulation and forms heavily in your work with PHP
and I recommend that you consult the PHP manual frequently for information
on special string manipulation functions.
17
<?php
//if, elseif and else statements
$a = 2; $b = 3;
//While loop
//Prints the numbers 1 through 10
$i = 1;
while ($i <= 10) {
print $i++;
//the printed value would be
//$i before the increment
//(post-increment)
}
//For loop
//Prints the numbers 1 through 10
for ($i = 1; $i <= 10; $i++) {
print $i;
}
18
case 2:
print "i equals 2";
break;
}
//Prints "i equals 1"
?>
Use this brief review of the control structures as inspiration and consult the
PHP manual for details on syntax and variations of these control structures.
5.4 Functions
Functions are an essential part of any structured programming language. You
can think of functions as boxes you can feed values (arguments); the functions
process the arguments and return a result to the user (return value). PHP syntax
for creating such structures looks like this:
<?php
//Print 4
echo add_values(2,2);
?>
Arguments and return values can be any of the mentioned data types. You
should be aware that global variables (variables declared outside a function) are
not defined within a function unless explicitly stated with the global keyword:
<?php
$num1 = 2; $num2 = 2;
function add_values() {
//Import globals
global $num1, $num2;
//Calculate result
$result = $num1 + $num2;
return $result;
}
//Print 4
//Function with no arguments
echo add_values();
?>
19
5.5 Getting more information on the PHP language
With this brief review of the PHP language you should be able to get started
and to understand the examples in the remainder of this document. You will
however need more information on the PHP language as you move further.
The PHP web site (www.php.net) is an excellent resource for documentation,
downloads and links.
6 Interfacing databases
The number one reason to use server side scripting is probably to interface
databases. There are so many advantages to storing your web content in a
database and generate web pages on the fly and most of the programming pro-
cedures are quite simple, making it easy to get started. In this section we will
review some of the basic techniques for interfacing databases. Most of the basic
procedures are the same regardless of platform and database engine, but there
are some syntactical differences, and therefore we will review two scenarios: 1)
The classic apache web server and MySQL database and 2) the Microsoft way
(IIS and Access). But before we come to that we will need to take a look at an-
other programming language used to communicate with databases: Structured
Query Language (SQL).
20
It can be extended in many ways to include information from several tables etc.
Suppose you have a table in a database looking like this:
+----+-----------------------+------------+
| ID | name | startprice |
+----+-----------------------+------------+
| 1 | Michael Schumacher | 65 |
| 2 | Mika Hakkinen | 63 |
| 3 | David Coulthard | 50 |
| 4 | Rubins Barrichello | 46 |
| 5 | Jacques Villeneuve | 37 |
| 6 | Juan-Pablo Montoya | 32 |
| 7 | Ralf Schumacher | 40 |
| 8 | Giancarlo Fisichella | 25 |
| 9 | Oliver Panis | 23 |
| 10 | Heinz-Harald Frentzen | 20 |
| 11 | Jenson Button | 18 |
| 12 | Jarno Trulli | 16 |
| 13 | Nick Heidfeld | 11 |
| 14 | Jean Alesi | 10 |
| 15 | Eddie Irvine | 9 |
| 16 | Pedro de la Rosa | 8 |
| 17 | Luciano Burti | 8 |
| 18 | Kimi Raikkonen | 7 |
| 19 | Jos Verstappen | 7 |
| 20 | Enrique Bernoldi | 6 |
| 21 | Fernando Alonso | 5 |
| 22 | Tarso Marques | 4 |
+----+-----------------------+------------+
This is a table with 3 fields: ID, name and startprice. The table is called
drivers. If we wanted to select everything from this table we would write:
SELECT * FROM drivers
In many situation we would want to be a bit more specific. For instance we
might only be interested in a specific driver:
SELECT * FROM drivers WHERE ID = 14
This statements produces:
+----+------------+------------+
| ID | name | startprice |
+----+------------+------------+
| 14 | Jean Alesi | 10 |
+----+------------+------------+
Also we might not be interested in all the fields in the table:
21
+--------------------+------------+
| name | startprice |
+--------------------+------------+
| Michael Schumacher | 65 |
| Mika Hakkinen | 63 |
| David Coulthard | 50 |
| Rubins Barrichello | 46 |
| Jacques Villeneuve | 37 |
+--------------------+------------+
And that is basically what you need to extract basic information from tables.
Some of the later examples might be slightly more complicated, but the basic
concept is the same.
22
6.2.1 Creating a database and a database user
Before we can manipulate data, we need to create a database and a database
user with the proper rights to manipulate the data. If you are already familiar
with creating databases and users in MySQL you can skip this section.
First you must log into the database. Type the following on the command
prompt:
[foo@bar fubaroh]$ mysql -u root -p
Enter password:
The login procedure should look something like the example above. You need to
know the root password for the MySQL server on your system. If it is a newly
installed system, the password is empty and you can just press enter to log in.
Your screen should look like this:
mysql>
Start by creating a new database:
mysql> create database testdb;
Query OK, 1 row affected (0.16 sec)
You then need to start using that database and create a table in the database:
mysql> use testdb
Database changed
23
mysql> SELECT * FROM people;
+----+---------+------+
| id | name | age |
+----+---------+------+
| 1 | Michael | 88 |
+----+---------+------+
1 row in set (0.00 sec)
Notice that the id field has been set automatically to 1.
The last thing we need to do is to create a user for access to the database.
When connecting to the database from a PHP script, we need to specify a user.
If we use the root user, the script will in principle have unlimited rights. As
this represents a security risk we will create a user with limited rights and use
that user for access to the database.
The MySQL database has a privilege system. The system allows you to spec-
ify valid users and furthermore to specify what databases, tables and columns
the user have access to. You should consult the MySQL manual [5] for details
on the privileges system. The following illustrates how to create a user:
mysql> use mysql
Database changed
24
mysql> INSERT INTO people (name, age) VALUES (Peter, 34);
Query OK, 1 row affected (0.00 sec)
<head>
<title>Extracting data</title>
</head>
<body>
<h1>Extracting data</h1>
<table border="1">
<tr>
<th>ID</th><th>Name</th><th>Age</th></tr>
<tr>
<?php
//Select a database
mysql_select_db("testdb",$link);
25
//Create a variable holding
//the SQL statement.
$sql = "SELECT * FROM people";
</html>
The example above can be used as a model whenever you need to send SELECT
queries to the database.
</head>
<title>Create new record</title>
</head>
<body>
<h1>Create new record</h1>
<form action="create.php" method="post">
Name:<br>
<input type="text" name="name">
<p>
Age:<br>
<input type="text" name="age" size="2">
<p>
<input type="submit"> <input type="reset">
26
</form>
</body>
</html>
Notice that the form sends the values from the form to a script called create.php.
With our knowledge of SQL and how values are passed from forms to scripts, it
is easy to implement the create.php script:
<html>
<head>
<title>Execute INSERT statement</title>
</head>
<body>
<h1>Execute INSERT statement</h1>
<?php
$link = mysql_connect("localhost","testuser","testpass");
mysql_select_db("testdb",$link);
mysql_close($link);
?>
</body>
</html>
This script follows almost the same model as the script for extracting data. The
only real difference is the SQL statement. In this case it is an INSERT statement
instead of SELECT. A thing to notice is the primitive error handling. The script
uses the function mysql_error() to check if the SQL statement generated any
errors.
27
http://www.someserver.com/somefolder/editor.php?id=2
Parameters passed in query strings like above are available in the PHP scripts
as variables just like the parameters passed with the post method from forms.
The script editor.php would, in the case above, have a variable called $id with
the value 2. This makes it very easy to create an editor for the records. We will
design the editor in such a way, that it returns to the extraction script (the list
of data in the table) when the changes have been saved:
<?php
$link = mysql_connect("localhost","testuser","testpass");
mysql_select_db("testdb",$link);
?>
<html>
<head>
<title>Editor</title>
</head>
<body>
<h1>Editor</h1>
Editing record number: <?= $id ?> <br>
<p>
<form action="editor.php" method="post">
Name:<br>
28
<input type="text" name="name" value="<?= $person["name"] ?>">
<p>
<input type="text" name="age"
size="2" value="<?= $person["age"] ?>">
<p>
<input type="submit"> <input type="reset">
<input type="hidden" name="id" value="<?= $id ?>">
<input type="hidden" name="change" value="1">
</form>
</body>
</html>
Although the database manipulation in this script is rather primitive, it does
contain a few new interesting features:
The first thing to notice is the check to see if there is a value in the param-
eter $id. If not, the users browser is directed to another page by sending
a header field instead of a web page. The Location header field causes the
browser to be redirected to another page. The header() function should
be used before any HTML in the document. The HTML causes the stan-
dard headers fields to be sent, and this prevents the header() function
from working properly.
There is also a check to see if the field variable named $change is defined.
This variable corresponds to a field in the form generated by the page
if $change is not defined. The field in the form is of type hidden. This
means that the field will not be visible to the user (unless he looks at the
source code) but the value will be sent. This is an easy way to send values
to scripts without the user knowing it.
The script takes advantage of a quick way to escape HTML mode and print
the value of a single expression in the document. The syntax <?= $id ?>
makes the script print the value of the $id variable in the resulting HTML
document. It is not particularly efficient to escape HTML mode multiple
times, but it can be very advantageous in situation such as the one above.
<head>
<title>Extracting data</title>
</head>
<body>
29
<h1>Extracting data</h1>
<table border="1">
<tr>
<th>ID</th><th>Name</th><th>Age</th></tr>
<tr>
<?php
//Select a database
mysql_select_db("testdb",$link);
</html>
This concludes the tour of the basic MySQL facilities in PHP. There are many
other available database functions. Consult the PHP manual.
30
Access database is general for all ODBC calls. This means, that if you wish to
use another database than MySQL or Microsoft Access, the syntax need not be
changed at all as long as your database system has an ODBC driver.
There will be no explanation on creating and editing databases with Mi-
crosoft Access in this manual.
<head>
<title>Extracting data</title>
</head>
<body>
<h1>Extracting data</h1>
<table border="1">
<tr>
<th>ID</th><th>Name</th><th>Age</th></tr>
<tr>
<?php
31
//Notice that no username and password is supplied
//Access does not offer this kind of protection
</html>
The example above can be used as a model whenever you need to send SELECT
queries to the database.
</head>
<title>Create new record</title>
</head>
<body>
<h1>Create new record</h1>
<form action="create.php" method="post">
Name:<br>
<input type="text" name="name">
<p>
Age:<br>
<input type="text" name="age" size="2">
<p>
32
<input type="submit"> <input type="reset">
</form>
</body>
</html>
Notice that the form sends the values from the form to a script called create.php.
With our knowledge of SQL and how values are passed from forms to scripts, it
is easy to implement the create.php script:
<html>
<head>
<title>Execute INSERT statement</title>
</head>
<body>
<h1>Execute INSERT statement</h1>
<?php
$link = odbc_connect("testdb","","");
odbc_close($link);
?>
</body>
</html>
This script follows almost the same model as the script for extracting data. The
only real difference is the SQL statement. In this case it is an INSERT statement
instead of SELECT. A thing to notice is the primitive error handling. The script
uses the function odbc_error() to check if the SQL statement generated any
errors.
33
to display from a query string in the URL. If we want to edit the record with
id = 2, we could type the following URL in the browser:
http://www.someserver.com/somefolder/editor.php?id=2
Parameters passed in query strings like above are available in the PHP scripts
as variables just like the parameters passed with the post method from forms.
The script editor.php would, in the case above, have a variable called $id with
the value 2. This makes it very easy to create an editor for the records. We will
design the editor in such a way, that it returns to the extraction script (the list
of data in the table) when the changes have been saved:
<?php
$link = odbc_connect("testdb","","");
?>
<html>
<head>
<title>Editor</title>
</head>
<body>
<h1>Editor</h1>
Editing record number: <?= $id ?> <br>
34
<p>
<form action="editor.php" method="post">
Name:<br>
<input type="text" name="name" value="<?= $person["name"] ?>">
<p>
<input type="text" name="age"
size="2" value="<?= $person["age"] ?>">
<p>
<input type="submit"> <input type="reset">
<input type="hidden" name="id" value="<?= $id ?>">
<input type="hidden" name="change" value="1">
</form>
</body>
</html>
Although the database manipulation in this script is rather primitive, it does
contain a few new interesting features:
The first thing to notice is the check to see if there is a value in the param-
eter $id. If not, the users browser is directed to another page by sending
a header field instead of a web page. The Location header field causes the
browser to be redirected to another page. The header() function should
be used before any HTML in the document. The HTML causes the stan-
dard headers fields to be sent, and this prevents the header() function
from working properly.
There is also a check to see if the field variable named $change is defined.
This variable corresponds to a field in the form generated by the page
if $change is not defined. The field in the form is of type hidden. This
means that the field will not be visible to the user (unless he looks at the
source code) but the value will be sent. This is an easy way to send values
to scripts without the user knowing it.
The script takes advantage of a quick way to escape HTML mode and print
the value of a single expression in the document. The syntax <?= $id ?>
makes the script print the value of the $id variable in the resulting HTML
document. It is not particularly efficient to escape HTML mode multiple
times, but it can be very advantageous in situation such as the one above.
<head>
<title>Extracting data</title>
35
</head>
<body>
<h1>Extracting data</h1>
<table border="1">
<tr>
<th>ID</th><th>Name</th><th>Age</th></tr>
<tr>
<?php
</html>
This concludes the tour of the basic ODBC facilities in PHP. There are many
other available database functions. Consult the PHP manual.
References
[1] PHP manual. Url: http://www.php.net/manual. Complete online reference
with comments from users.
36
[2] Michael Schacht Hansen. A short introduction to HTML and CSS. Url:
http://www.intermed.dk/php.
[3] Gnu emacs. Url http://www.gnu.org/software/emacs. A free, multipurpose
texteditor. Features highligting for several programming languages.
[4] Ultraedit. Url http://www.ultraedit.com. A shareware, multipurpose texte-
ditor. Only available for Windows.
37