What have sprint.ca, livebid.amazon.com, xoom.com, and mp3.lycos.com
in common? All employ one of the Web's hottest server side technologies:
PHP, the PHP Hypertext Preprocessor.
While the success of Open Source software like Linux or Apache has been
documented extensively throughout all mainstream media, the rise of PHP
has gone largely unnoticed. Still, the Web scripting language PHP is the
most popular module for the Apache Web server, according to a E-Soft survey
(http://www.e-softinc.com/survey/). Netcraft studies have found that PHP
is in use on over 6% of all Web domains in the world (see http://www.netcraft.com/survey).
That is an incredible market penetration for a rather specialized product.
This popularity continues to rise exponentially, with the new version 4.0
just around the corner. Increasingly, this is being reflected in traditional
media: By May 2000, more than 20 books about PHP have been published in
different languages, with more in the pipeline. Commercial players are
beginning to join the bandwagon: PHP is included with Web servers, for
example C2's Stronghold, and Linux distributions. A new company, Zend Technologies,
has been formed to provide commercial add-ons and support for PHP. A long
list of large-scale Web sites employ PHP, as well as hundreds of thousands
small to medium Web sites.
As Web sites and intranets get larger and more complex, static HTML
files hit their limits. Today, the Web is an interactive, transaction-oriented
business platform, featuring advanced Web-based applications such as online
commerce, business information systems, and collaborative computing environments.
To develop such applications, you need a technology to generate dynamic
content for Web pages. PHP is one of the technologies.
In technical terms, PHP is a cross-platform, HTML-embedded, server-side
web scripting language. You can run most PHP code, without alteration,
on computers running many different operating systems. A PHP script that
runs on Linux will generally run on Windows as well. It is HTML-embedded
because PHP code is written in files containing a mixture of PHP instructions
and HTML code. The PHP programs are run on a server - specifically, a web
server. We accesss the web server on which they reside, and this runs the
program, sending any resulting output back to the browser.
Wonderful things come from singular inspiration. PHP began life
as a simple way to track visitors to Rasmus Lerdorf's on-line resume. It
also could embed SQL queries in Web pages. But as often happens on the
Web, admirers quickly asked for their own copies. Being a proponent of
the Internet's ethic of sharing, not to mention being a generally agreeable
guy, Rasmus unleashed Personal Home Page Tools version 1.0 upon an unsuspecting
Web.
Unleashed upon himself may be more accurate: PHP became very popular. A consequence was a flood of suggestions. PHP 1.0 filtered input, replacing simple commands for HTML. As its popularity grew, people wondered if it couldn't do more. Loops, conditionals, rich data structures: All the conveniences of modern structured programming seemed like a next logical step. Rasmus studied language parsers, read about YACC and GNU Bison, and created PHP 2.0.
PHP 2.0 allowed developers to embed structured code inside HTML tages. PHP scripts could parse data submitted by HTML forms, communicate with databases, and make complex calculations on the fly. And it was very fast because the freely available source code compiled into the Apache Web server. A PHP script executed as part of the Web server process and required no forking, often a critism of CGI scripts.
PHP was a legitimate development solution and began to be used for commercial Web sites. By January of 1999 the PHP Web site reported almost 100,000 Web sites were using PHP.
A community of developers grew up around PHP. Feature requests were
balanced by bug fixes and enhancements. Then a new parser was written after
it is realized that PHP 2.0 was the source of many problems. Rasmus decided
to work on PHP 3.0. After seven months of developments, PHP version 3.0
was released on June 6, 1998. And more than a year later, comes PHP version
4, the most recent version, with a bunch of new features.
The days of the static Web sites with HTML files and a few CGI scritpts
are over as today's web sites must be dynamic. The toughest decision facing
the creator of a Web application is choosing from hundreds of technologies.
Perl has adapted well to being a CGI solution and it has been used to drive complex Web technology like CyberCash and Excite's EWS search engine. Microsoft provides its Active Server Pages with Internet Information Server. Middleware is yet another solution. Server-Watch.com lists hundreds of Web technologies. Why should you choose PHP over any of these alternatives?
The short answer is that PHP is better. It is faster to code and faster to excute. The same PHP code runs unaltered on different Web server and different operation systems. And functionality that is standard with PHP is an add-on in other environments. A more detailed argument follows.
PHP is free. Anyone may visit the PHP Web site and download the complete source code. Binaries are also availalbe for windows. The result is easy entry into the experience. There is very little risk in trying PHP, and its license allows the code to be used to develop works with no royalies. Even commercial giants like Netscape recognize the advantages of making source code available.
Open Source software in general means a number of significant advantages for the corporate IT infrastructure. Because the full source code is available, it can be inspected in thorough security audits. If third parties find security issues, they're usually fixed within hours or days. If no one is going to do it, you can assign your own personnel to it - with the full code in your hands, you're no longer dependent on external software manufacturers.
When mentioning Java, one of its key features comes to mind instantly: portability. Up until version 3.0, PHP could be integrated only as module into the Apache Web server, or run as separate CGI program, which would eliminate many of PHP's speed benefits. In version 4.0, however, the Web server interface (Server API, or SAPI) has been abstracted, and PHP now integrates well with different Web servers: iPlanet/Netscape Enterprise Server, IIS, Apache, Zeus, fhttpd, and so forth. Platform independence has always been an advantage of PHP: It runs on all popular Unix platforms, including Linux, on Windows, on MacOS, and even on OS/2.
The broad platform support can be directly attributed to the fact that PHP is distributed with full source code. Anyone with the necessary skills can port PHP to a new operating system. The resulting modifications to the core system can then be contributed back to the community.
The syntax and grammatical structure of PHP resembles the C programming language with the complexity (for example, memory management, pointers, and strong typing) taken out. The developers of PHP aren't hesitant to integrate the best features of other languages, though, so you'll find elements of Perl and Java in PHP as well. For programmers familiar with C, Perl, or Java, it is a matter of days to get acquainted with PHP. Thanks to the excellent reference manual, anyone of your developers can probably produce small database enabled applications after just one afternoon.
Since version 4.0, PHP supports direct access to Java objects on any system with a Java Virtual Machine available, as well as Distributed COM on Windows. Multiple Web applications can reuse the same components. This enables you to keep your business logic in separate components, and use PHP for what it does best, and where it outperforms its alternatives: Web application development. This means a significantly lower Cost of Ownership: It enables business to leverage existing technology and develop new applications in an easier way.
Also PHP is modifiable. PHP has been designed to allow fortune extension of functionality. It's coded in C and provides a well_defined API(Application Programming Interface). Praggrammers may add new functionality easily. The rich set of functions available in PHP are evidence they often do.
PHP can enforce a cleaner separation of layout and application logic. When embedding the script directly in HTML, average, HTML-literate Web designers cannot easily edit the contents of the page without being familiar with the scripting language used. PHP offers a variety of libraries to work with page templates, which solve this problem, and introduce an efficient development methodology and simplify maintenance. This way, developers focus on the application logic, and designers can change the layout of a dynamic page without involving the developer or interfering with the program logic. This translates into faster application development, and makes maintenance tasks easier by dividing them into content and logic tasks, which can be handled by separate team members.
Abundant Connectivity. And there's a lot to explore. For example, PHP implements native interface to a wide variety of database engines, from Open Source systems like MySQL or PostgreSQL to commercial products like Oracle, SQL Server, DB2, and many more. The native database access offers better performance and tighter control than layered access methods such as ODBC (which is still available for databases not supported natively). Especially on the Web, a fast response time is crucial for the success of applications.
Besides databases, PHP supports most current Internet standards: IMAP, FTP, POP, XML, WDDX, LDAP, NIS, and SNMP. For corporate and IT needs, this simply means that PHP is able to talk to different standards and technologies with ease: All from one common tool set, without the need for expensive third party modules.
PHP needs not be used for Web development exclusively. It can also be compiled as stand-alone script interpreter, and handles simple system administration tasks as well. For example, you could use a small PHP script to send daily statistics from your e-commerce application. In version 4.0, the language core engine, the Zend parser, has been abstracted enough to be embeddable in other technologies. Rumors go that is planned to integrate PHP as stored procedure language into the popular MySQL database system. Seeing the dynamic evolution of PHP, it is only logical to expect the language to grow into other scenarios - why not use PHP as a macro processor in a word processor?
Then there's the community. Free help is available from mailing lists,
newsgroups, and IRC channels. The PHP core developers participate in these
support forums, and provide developers with top-level advice - usually
within hours.
PHP scripts are often embedded in the HTML code of page, and then
get parsed on the server-side - the browser sees plain HTML only. PHP exists
as a tag inside an HTML file. It begins with a less than symbol, or opening
angle bracket-<, and ends with a greater than symbol, or closing angle
bracket->. It uses question mark - ? folowing the opening angle bracket
to distinguish itself from other tags. All text outside the PHP tag is
simply passed through to the browser. Text inside the tag is expected to
be PHP code and is parsed. A typical Hello-World script looks like this:
<html>
<? print("Hello World!");?>
</html>
Putting "php" after the opening question mark makes PHP code more friendly to XML parsers. Alternatively you may use a script tag as if you were writting JavaScript. Since PHP exists inside an HTML file, like HTML it is written completely with ASCII text editors.
An ordinary HTML page with one remarkable difference is (see Figure
1: Printing Today's Date): the PHP code between the <? and ?>. When
this page is passed through the PHP module, it will replace the PHP code
with today's date. It could be: "Tuesday February 27, 2001".
<HTML>
<HEAD>
<TITLE>Figure 1<TITLE>
</HEAD>
<BODY>
Today's Date: <? print(Date("l F d, Y")); ?>
</BODY>
</HTML>
Ouput :
Today's Date: Tuesday February 27, 2001
Figure 1 Printing Today's Date
White space is ignored by PHP. The next example is functionally the same as the above one, though it may be easier to notice it contains PHP code. Also the comment between the /* and the */ is same as whitespace. Double_slashes or a pound will build a single_line comment. The parser ignores the comment.
After skipping over the whitespace and the comment from in Figure 2, the parser encounters the first word: print. It's the PHP's command. It sends to the browser. The rest of the line will be evaluated and if it produces output, print will pass it along to the browser. PHP uses a semicolon to denote the end of a line.
<HTML>
<HEAD>
<TITLE>Figure 2<TITLE>
</HEAD>
<BODY>
Today's Date:
<?
/*
** print today's date
*/
print(Date("l F d, Y"));
?>
</BODY>
</HTML>
Figure 2 Reformatting for Readability
The contents of the line between print and ; is a call to a function
named date. The text between the opening and closing parentheses is the
parameter passed to date. The parameter tells date in what form you want
the date to appear. The string of characters between double quotes is called
a string constant. PHP knows that when quotes surround charaters you mean
them to be treated as text. Without quotes, PHP will assume you are naming
a function or some other part of the language itself. Notice that print
is typed completely in lowercase letters, yet date has a leading uppercase
letter. PHP takes a very lenient attitude about the names of its built_in
functions.
We all have some experience with CGI script. When a Web server gets
a request for a CGI, it can't just send the contents of the file. It must
execute the script first. The script will generate some HTML code which
then gets sent to the browser. As far as the browser is concerned, it's
just getting HTML. The Web server does a bunch of work that it gets very
recognition for, but Web servers rarely get the respect they deserve. The
medium is definitely not the message. When a PHP is requested, it is processed
exactly like a CGI, at least to the extent that the script is not simply
sent to the browser. It is first passed through the PHP engine which gives
the Web server HTML text.
Reading and thinking are just the beginning of learning a new programming
language. The best approach is to try code verbatim. If that works, change
something and see if it still works. That's hacking. If you're in the environment
in which the many Web hosts that offer PHP. You'll only need to find
out what file extention they have chosen for PHP, usually .php3, and jupload
some scripts. Web server usually decide how to process files based on their
name, particularly by their dot extension. If you need to set up the envorinment,
you have several options. The first one is whether you will be using Apache
or another Web server. PHP may plug into Apache as a module. This allows
PHP to run much faster because a new shell process isn't created for every
PHP page served. If you won't be using Apache, then PHP will exist as a
seperate executable that processes scripts and passes them to the Web server.
Anybody capable of compiling and installing Apache should have little trouble
with installing PHp. The installation instructions found on the PHP Web
site, www.php.net, are the best place to go.
PHP works as a script engine with Microsoft Internet Infronation Server,
but work is underway to make it an ISAPI dynamic link library. This makes
it roughly equivalent to an Apache module. If you have difficulty getting
PHP to communicate with your Web server, the PHP3 mailing list is a good
place to ask questions.
PHP's data types are string, integer, double, array, object.
When you can concatenate strings,
$Car = $CarType . $EngineSize;
the result of "Cardillac2.6" will be assigned to the variable $Car.
Numeric data types, integer and double works the same way as in C and
JAVA.
The declaration and initialization of variables of array data type
$Author[] = "William Shakespeare";
$Author[] = "Franz Kafka";
is the same as
$Author[0] = "William Shakespeare";
$Author[1] = "Franz Kafka";
Alternatively, you can do it as the following way:
$Author = array ("William Shakespeare", "Franz Kafka");
Iterating through an array:
for($index = 0; $index < 2; $index++) {
echo "<BR>$Author[$index]";
}
String-indexed array is the same as hash tables in Perl:
$StateCapital = array ("ga" => "Atlanta", "il" => "Springfield"},
or alternatively,
$StateCapital["ga"] = "Atlanta";
$StateCapital["il"] = "Springfield";
You can traverse this string-indexed array as follows:
while (list ($State, $Capital) = each ($StateCapital)) {
echo "<BR>$State - $Capital";
}
You can also alternatively traverse the arrays using foreach statement
as in Perl.
<HTML>
<HEAD>
<TITLE>Figure 6</TITLE>
</HEAD>
<BODY>
<H1>
Today's Date:
<?
/*
** get today's date of the week
*/
$Today = date("l");
if ( $Today == "Friday") {
print ("Thank Goodness
It's Friday!");
} else {
print("Today is $Today");
}
?>
</H1>
</BODY>
</HTML>
Figure 3 Conditional Daily Message
<HTML>
<HEAD>
<TITLE>Figure 4</TITLE>
</HEAD>
<BODY>
<H1>Today's Daily Affirmation</H1>
<?
for ( $count =1; $count
<= 3; $count++)
{
print ("<B>$count</B>
I'm good enough, ");
print ("I'm smart
enough, ");
print ("and, doggone
it, people like me!<BR>\n");
}
?>
</BODY>
</HTML>
Figure 4 Today's Daily Affrimation
function tax ($Salary) {
$Salary = $Salary - (($Salary/100)*20);
return $Salary;
}
PHP has a set of its own predefined functions, such as sort(), rsort(), arsort(), array_push(), array_pop(), etc.
Example of using predefined functions:
$Author[0] = "William Shakespeare";
$Author[1] = "Franz Kafka";
sort($Author);
The result will be
$Author[0] = "Franz Kafka";
$Author[1] = "William Shakespeare";
Scripts become much more useful when they use input from the user.
When you call PHP from the HTML form, the form fields are turned into variables.
Figure 5 is a form that calls Figure 6 a further modification of our example
script. Figure 5 is a standard HTML form. It looks very similar to CGI.
When the user presses th submit button, the script named in the ACTION
attribute will receive the three form fields and PHP will convert them
into variables. One thing you should notice that if you put words where
the script expects numbers, PHP seems to just assign them values of zero.
The variabels are set with a test string and when the script tries to treat
it as a number, PHP does it best to convert the information. Entering "10
Little Indians" for the cost of lunch will be interpreted as 10.
< HTML>
<HEAD>
<TITLE>Figure 5</TITLE>
</HEAD>
<BODY>
<FORM ACTION="5.php4" METHOD="post">
Your Name:
<INPUT TYPE="text" NAME="YourName"><BR>
Days Buying Lunch:
<INPUT TYPE="text" NAME="CostOfLunch"><BR>
<INPUT TYPE="submit" >
</FORM>
</BODY>
</HTML>
Figure 5 HTML Form for Lunch Information
<?
$Today = Date("l F d,Y");
?>
<HTML>
<HEAD>
<TITLE>Figure 6</TITLE>
</HEAD>
<BODY>
Today's Date:
<?
/*
** print today's date
*/
print("<H3>$Today</H3>\n");
/*
** print message about lunch cost
*/
print ("$YourName, you will be out :");
print($CostOfLunch * DaysBuyingLunch);
print(" dollars this week. <br>\n");
?>
</BODY>
</HTML>
Figure 6 Computing the Cost of Lunch from a Form
open and close a file
read from and write to a file
delete and rename a file
navigate within a file
open and close a file
read the directory entries
delete and rename a directory
Example for opening a file:
$fp = fopen("./data.txt", "r");
if(!$fp) die("can't open the file");
See the similarities between these functions and those in C.
1. Open a connection to the server.
2. Work with databases in the server.
3. Close the connection.
PHP has a full set of functions to fulfill the above listed tasks.
For example, to connect to MySQL
in PHP code, you use the following function
$link_id = mysql_connect("localhost", "phpuser", "phppass");
Once your PHP code has connected with the database, it can create tables,
drop tables, update, retrieve
data from the database using specific functions. After finishing, close
the connection by mysql_close(
$link_id). That is, you can embed all these functions in your PHP code.
Considering the vastly growing amount of servers on which PHP is
now running, taking a look at the huge step PHP made from version 3.0 to
version 4.0, and seeing its mature and up-to-date base, PHP has surely
become what it has been aiming at: A great tool for rapid development of
stable and fast Web applications. If you want to be good at Web applications,
you should certainly consider PHP. Gone are the days, when a business could
post static pages on a Web site - today, sophisticated Web applications
demand that companies use technologies that can provide them with rapid
development, performance, scalability, openness, and security - and PHP
is a strong option in the Web application development area.
PHP Homepage: http://www.php.net
Zend Homepage: http://www.zend.com
Core PHP Programming by Leon Atkinson, 1999
Beginning PHP4 by Wankyu Choi, 2000