Zend - The php Company     Register |  Log in |  My Zend |     
 
 
PHP 5
PHP General
PEAR and PECL
Forums
Resources
Articles
Tutorials
Tips & Tricks
Documentation
Code/App Gallery
Community
Code News
Downloads
Partners

View printable format View printable format
Send this article to a friend Send this article to a friend
Notify me when a new article appears Notify me when a new article appears

Preview Introduction to PHP Notify me when a new spotlight appears Send this article to a friend View printable format Next
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:

  1. A numerically indexed array with indices running from 0 to 4.
  2. An associative array with string indices.
  3. A numerically indexed array, with indices running from 5 to 7.
<?php

$array1 
= array(235711);
$array2 = array("one" => 1"two" => 2"three" => 3);
$array3 = array(=> "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.

CGI/Web server provided variables

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)


Readers' Comments

Begin a new thread

+ Expand tree

    question please?
lzy
03/06/2001 12:16
    HOW to start php script ????
Nacho Nachev
18/07/2001 00:43
    do..while -loops
Arne Caspari
26/07/2001 11:34
    How to enable XSLT w/ CGI PHP in IIS
Andrew Bantly
28/07/2001 00:54
    Initalizing PHP
Skip
25/09/2001 05:42
    Thanks
Craig Daniels
28/09/2001 19:08
    Nice Overview
Annette
31/10/2001 02:40
    PHP with PWS on Win98
sunjay
08/11/2001 19:51
    PHP vs XML
Stephen Parry
15/11/2001 02:41
    posting/HTML
andrew
17/11/2001 06:20
    Nice intro
cdx
24/12/2001 05:26
    acronym question
chris hughes
25/01/2002 12:54
    Support for MS Access
Muhammad Yousaf
28/01/2002 16:30
    PHP and Web Server File System
John Coffey
14/02/2002 21:39
    HOW DO I INITIALISE PHP ON LINUX 7.2 OS
vivek
16/02/2002 16:02
    php to sybase
ning-wei
14/03/2002 14:20
    form values
Gabriel Oprea
14/03/2002 20:59
    PHP with Windows
Jairo
18/03/2002 18:22
    hosting
B34ST
21/04/2002 18:30
    How to start PHP script ????? (2)
Rising Star UK
31/05/2002 11:27
    Intro is Excellent
stevearino
24/06/2002 02:06
    PHP-Windows
Manisha
02/07/2002 14:25
    Nicely written introduction to PHP
Harris
06/07/2002 20:48
    Help
Chris
25/08/2002 02:40
    Good
Sivakumar Govindarajen
28/08/2002 15:04
    superb use of colours
tom
04/09/2002 19:53
    Very nice intro to PHP
Nick
24/09/2002 15:30
    Multiple Pages (able to Next and Back)
Are Morch
01/10/2002 23:16
    Associative arrays with mysql
Sarbjeet Rana
05/10/2002 21:13
    PHP behavior has changed, here's a quick update
philip olson
09/10/2002 03:33
    This is the best PHP site I come across yet.
ASP Man
13/11/2002 19:44
    kewl
B Pope
03/01/2003 05:23
    Embedding PHP engine in my own application
Felix
04/01/2003 01:24
    How to open a php file
Anna
26/01/2003 15:48
    Retain Formatting
Subash
02/04/2003 19:41
    .html wont do php
mark
29/04/2003 00:14
    Total Noob
Nish
11/08/2003 04:26
    World
Harry
10/09/2003 10:45
    How to make order form using PHP
sANG
01/10/2003 01:40
    Starting PHP - HELP!!
steve walker
26/12/2003 20:41
    Ok, deep trouble here!
Sage
05/01/2004 11:00
    elp!..deep down I am scared
scanner
06/03/2004 13:51
    problem w mail f-tion
Rimas
28/04/2004 22:23
    order form with java script
Bugi Gand
17/06/2004 23:47
    problem insert data to database using php/mysql..
ifa
24/06/2004 05:55
    Need help with PHP and linking to newswires
Keon P
11/08/2004 18:18
    Problem with session variable
Hanas
22/11/2004 09:00
    Updating a database with loops
Bill
08/12/2004 22:09
    Update Database fields with loops
William Stickles
08/12/2004 23:32
    Php_Script_Doubts
Namatchivayam
18/02/2005 13:29
    abc of PHP
Shahjahan Mondal
16/05/2005 18:53
    Basket Update
Colin
18/05/2005 17:11
    HTML parameters to PHP
Joseph Pellicano
09/09/2005 18:22
    php variable problem
oï¿œuz
30/09/2005 11:53
    Attach file with email problem
anil jain, Jaipue(India)
30/09/2005 13:31