By Stig Sæther Bakken with Zend staff
April 17, 2000
Intended Audience
How PHP came into being
Why yet another language?
PHP 4 Architecture
PHP 4 Architecture
Language Syntax
Embedding PHP Code
Dynamic vs. Static Web pages
Variables
Arrays
Conditionals and Looping Constructs
Web Application Features
submit.php
Working With Cookies
Built-in Variables
PHP internal variables
CGI/Web server provided variables
HTTP Request Variables
Database Handling
Communication with MySQL
MySQL Example
Communication with Other Databases
For More Information
About the author: Stig's daily work is as a programmer and project manager
at Fast Search & Transfer in Trondheim, Norway and Boston, USA. For some of
the services developed by FAST using PHP, see alltheWeb.com, mp3.lycos.com,
richmedia.lycos.com and listeningroom.lycos.com.
Intended Audience
This article is intended for Web page developers and programmers considering
PHP as an alternative Web page development tool. Both PHP's history and major
features are discussed.
How PHP came into being
PHP started as a quick Perl hack written by Rasmus Lerdorf in late 1994. Over
the next two to three years, it evolved into what we today know as PHP/FI 2.0.
PHP/FI started to get a lot of users, but things didn't start flying until Zeev
Suraski and Andi Gutmans suddenly came along with a new parser in the summer of
1997, leading to PHP 3.0. PHP 3.0 defined the syntax and semantics used in both
versions 3 and 4.
Why yet another language?
People often ask " why invent yet another language; don't we have enough
of them out there"? It is simply a matter of "the right tool for the
right job". Many Web developers found that existing tools and languages
were not ideal for the specific task of embedding code in markup. Those
developers first collaborated with Rasmus and then later with Zeev and Andi, to develop a
server-side scripting language which they felt would be ideal for developing
dynamic Web-based sites and applications.
PHP was created with these particular needs in mind. Moreover, PHP code was
developed for embedment within HTML. In doing so, it was hoped that benefits
such as quicker response time, improved security, and transparency to the end
user would be achieved. Considering that almost a million and a half sites are
currently running PHP (at the time of this article's publication), it would appear that
these developers were right.
PHP has evolved into a language, or maybe even an environment, that has a
very specific range of tasks in mind. For this, PHP is, in Stig's humble
opinion, pretty close to the ideal tool.
PHP 4 Architecture
PHP has undergone major architecture changes since version 3. First of all,
the language parser itself has become a self-contained component called The Zend
Engine. Secondly, PHP function modules, now called PHP extensions, are also
basically self-contained. Thirdly, there is a Web server abstraction layer
called SAPI that greatly simplifies the task of adding native support for new
Web servers. SAPI also has the advantage of increasing PHP 4 stability, in
addition to supporting multi-threaded Web servers.
The following figure presents PHP 4's architecture. The top border of the
figure represents the programmer's interface (meaning all except for the Web
server):
PHP 4 Architecture
SAPI currently has server implementations for Apache, Roxen, Java (servlet),
ISAPI (Microsoft IIS and soon Zeus), AOLserver and of course CGI.
All of PHP's functions are part of one of the layers with a side facing up in
the architecture figure. Most functions such as the MySQL support, are provided
by an extension. Most extensions are optional. They can be linked into PHP at
compile time or built as dynamically loadable extensions that can be loaded on
demand.
Language Syntax
Most of PHP's syntax is borrowed from C, although there are elements borrowed
from Perl, C++ and Java as well. This article assumes that you are familiar with
C's syntax. However, don't panic if you're not.
Embedding PHP Code
To give you an idea of what embedding PHP would entail, consider the
following three "hello world" examples, all of which will give the
exact same output:
Example 1: HTML alone
Hello, World!
Example 2: PHP code alone
<?php print "Hello, World!"; ?>
Example 3: PHP embedded within HTML
<?php print "Hello,"; ?> World!
Web servers supporting PHP will, by default, scan a file in HTML mode. HTML
code will be passed over to the browser as usual, up until the server happens
upon a PHP line of code. In examples 2 and 3 above, the "<?php" tag
informs the server that PHP code is to follow. The server then switches over to
PHP mode in anticipation of a PHP command. The "?>" tag closes out
the PHP mode with the server resuming its scanning in HTML mode once more.
Embedding code in this manner is, conceptually, a more fluid approach to
designing a Web page because you are working within the output setting, namely
an HTML page. Traditionally, you had to fragment the output (i.e. the header,
body, footer etc..) and then put it into the code. Now we are inserting the code
directly into the output.
From our lone example, however, one might come to ask, "So, what's the
difference?" or "Why add extra code when HTML alone would do the
trick?".
Read on!
Dynamic vs. Static Web pages
The "Hello, World" example we chose would certainly not require you
to use PHP. That's because it is static, meaning its display will always remain
the same. But what if you wanted to greet the world in any number of ways? Say,
for example, "Bonjour, World!", or "Yo, World!" and so
on.
Since HTML tags are purely descriptive they cannot function as a variable.
Nor can they convey even the simplest of uncertainty such as a
"Bonjour" or a "Yo". You need a command language to handle
variability in a Web page. Based on either a conditional statement or direct
user input, a command language can generate the "static" HTML
necessary to correctly display a Web page's content.
Let us reconsider example #3. This time we want to let the user decide how to
greet the world:
Example 4: PHP embedded within HTML revisited!
<?php print $greeting, ", "; ?> World!
From the above example, $greeting is assigned a value, and together with
the comma and the word "World!", this value is sent to the
browser.
Dynamic Web page design, however, is more than just about inserting
variables. What if you wanted not only to greet the world in French, but also to
present the page using the colors of the French flag?
Both a Web page's structure as well as its content can be customized. This
means dynamic Web page programming can also entail on-demand Web page
building.
No static, here!
Variables
In PHP, a variable does not require formal declaration. It will automatically
be declared when a value is assigned to it. Variables are prefixed by a dollar
sign: ($VariableName ).
Variables do not have declared types. A variable's type does not have to be
fixed, meaning it can be changed over the variable's lifetime. The table below
list's PHP's variable types:
Type
|
Description
|
Integer
|
integer number
|
Double
|
floating point number
|
bool1
|
Boolean (true or false), available from PHP 4.0
|
Array
|
hybrid of ordered array and associative array
|
object2
|
an object with properties and methods (not discussed in this article)
|
In the following example, four variables are automatically declared by
assigning a value to them:
<?php
$number = 5;
$string1 = "this is a string\n";
$string2 = 'this is another "string"';
$real = 37.2;
?>
Arrays
PHP arrays are a cross between numbered arrays and associative arrays. This
means that you can use the same syntax and functions to deal with either type of
array, including arrays that are:
- Indexed from 0
- Indexed by strings
- Indexed with non-continuous numbers
- Indexed by a mix of numbers and strings
In the example below, three literal arrays are declared as follows:
A numerically indexed array with indices running from 0 to
4.
An associative array with string indices.
A numerically indexed array, with indices running from 5 to
7.
<?php
$array1 = array(2, 3, 5, 7, 11);
$array2 = array("one" => 1, "two" => 2, "three" => 3);
$array3 = array(5 => "five", "six", "seven");
printf("7: %d, 1: %d, 'six': %s\n", $array1[3], $array2["one"], $array3[6]);
?>
From the above example, the indices in the array1 are implicit,
while the indices in array2 are explicit. When specifically setting
the index to a number N with the => operator, the next value has the index
N+1 by default. Explicit indices do not have to be listed in sequential order.
You can also mix numerical and string indexes, but it is not recommended.
Conditionals and Looping Constructs
PHP includes if and elseif conditionals, as well
as while and for loops, all with syntax similar to C.
The example below introduces these four constructs:
<?php
// Conditionals
if ($a) {
print "a is true<BR>\n";
} elseif ($b) {
print "b is true<BR>\n";
} else {
print "neither a or b is true<BR>\n";
}
// Loops
do {
$c = test_something();
} while ($c);
while ($d) {
print "ok<BR>\n";
$d = test_something();
}
for ($i = 0; $i < 10; $i++) {
print "i=$i<BR>\n";
}
?>
Web Application Features
One of PHP's oldest features is the ability to make HTML form and cookie data
available directly to the programmer. By default, any form entry creates a
global PHP variable of the same name.
In the following example, a user name is retrieved and assigned to a
variable. The name is then printed by the sub-routine
"submit.php":
<FORM METHOD="GET" ACTION="submit.php">
What's your name? <INPUT NAME="myname" SIZE=3>
</FORM>
submit.php
<?php
print "Hello, $myname!";
?>
From the above example, note that variables can also be referenced from
within double quoted strings.
For more information on strings, refer to our tutorial "Using
Strings".
Working With Cookies
You can set cookies in the browser from PHP using the
setcookie() function. setcookie() adds headers to the
HTTP response. Since headers must be inserted before the body, you will need to
finish all of your setcookie() calls before any body output
(usually HTML) is printed.
The following example uses a cookie to store a form value until your browser
is terminated.
<?php
if (!$myname) {
print "What is your name? ";
print "<FORM ACTION=\"$PHP_SELF\" METHOD=\"GET\">\n";
print "<INPUT NAME=\"myname\" SIZE=20>\n";
print "</FORM>";
exit;
}
setcookie("myname", $myname);
?>
For more information on using cookies, refer to our tutorial "Feedback
Form with Cookies".
Built-in Variables
PHP has a number of built-in variables that give you access to your Web
server's CGI environment, form/cookie data and PHP internals. Here are some of
the most useful variables:
PHP internal variables
The $GLOBALS and $PHP_SELF variables shown in the table below are specific to
PHP:
Variable Name
|
Description
|
$GLOBALS
|
An associative array of all global variables. This is the only variable in
PHP that is available regardless of scope. You can access it anywhere without
declaring it as a global first.
|
$PHP_SELF
|
This is the current script, for example /~ssb/phpinfo.php3 .
|
The variables listed below are derived from CGI protocols.
Note that the $HTTP_*_VARS variables are available
only when the "track_vars" directive is enabled. You can
enable the directive by default when installing PHP with the
"enable-track-vars" switch set to configure. Alternatively, you can set it in
php.ini, or from your Web server's configuration.
Variable Name
|
Description
|
$DOCUMENT_ROOT
|
Your Web server's base directory with user-visible files.
|
$REQUEST_METHOD
|
The HTTP method used to access this page, for example GET or POST.
|
$REQUEST_URI
|
Full local part of the request URL, including parameters.
|
$HTTP_GET_VARS
|
An associative array with the GET parameters passed to PHP, if any.
|
$HTTP_POST_VARS
|
An associative array with the POST parameters passed to PHP, if any.
|
$HTTP_COOKIE _VARS
|
An associative array with the cookies passed by the browser, if any.
|
$SCRIPT_FILENAME
|
File name of the top-level page being executed.
|
$SCRIPT_NAME
|
Local URI part of the page being executed.
|
$SERVER_ADMIN
|
Server administrator's email address.
|
$SERVER_NAME
|
Domain name for the server.
|
$SERVER_PORT
|
TCP port number the server runs on.
|
$SERVER_PROTOCOL
|
Protocol used to access the page, for example "HTTP/1.1".
|
HTTP Request Variables
HTTP Request Variables are derived from their corresponding HTTP headers. For
example, $HTTP_USER_AGENT is derived from the User-Agent header, presented in
the table below:
$HTTP_HOST
|
Host name in the browser's "location" field.
|
$HTTP_USER_AGENT
|
User agent (browser) being used.
|
$HTTP_REFERER
|
URL of the referring page.
|
Database Handling
Communication with MySQL
PHP and MySQL are often referred to as the "dynamic duo" of dynamic
Web scripting. PHP and MySQL work very well together, in addition to the speed
and features of each individual tool.
The following is a simple example of how to dump the contents of a MySQL
table using PHP. The example assumes you have a MySQL user called
"nobody" who can connect with an empty password from localhost:
MySQL Example
In the example below, PHP implements the following procedure:
- Connect to MySQL.
- Send a query.
- Print a table heading.
- Print table rows until end of the table has been reached.
<?php
//Connect to the database on the server's machine as
//user "Nobody".
$conn = mysql_connect("localhost", "nobody", "");
$res = mysql_query("SELECT * FROM mytable", $conn);
$header_printed = false;
print "<TABLE>\n";
do {
$data = mysql_fetch_array($res);
// Retrieve the next row of data.
if (!is_array($data)) {
break;
}
// This part is done only on the first loop. It prints
// out the names of the fields as table headings. This
// ensures that the headings will only be printed if the
// database returns at least one row.
if (!$header_printed) {
print " <TR>";
reset($data);
while (list($name, $value) = each($data)) {
print " <TH>$name</TH>\n"
}
print " </TR>\n";
$header_printed = true;
}
print " <TR>\n";
print " <TD>";
// Instead of looping through the returned data fields,
// we use implode to create a string of all data items
// with the required HTML between them.
print implode("</TD>\n <TD>", $data);
print " </TR>\n";
} while ($data);
print "</TABLE>\n";
?>
Communication with Other Databases
Unlike other scripting languages for Web page development, PHP is
open-source, cross-platform, and offers excellent connectivity to most of
today's common databases including Oracle, Sybase, MySQL, ODBC (and others).
PHP also offers integration with various external libraries which enable the
developer to do anything from generating PDF documents to parsing XML.
For More Information
The following resources will further your knowledge of PHP:
The PHP Manual
The PHP FAQ
Support page (mailing lists and more)
|