O'Reilly logo

Programming PHP, 4th Edition by Peter MacIntyre, Kevin Tatroe

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 1. Introduction to PHP

PHP is a simple yet powerful language designed for creating HTML content. This chapter covers essential background on the PHP language. It describes the nature and history of PHP, which platforms it runs on, and how to configure it. This chapter ends by showing you PHP in action, with a quick walkthrough of several PHP programs that illustrate common tasks, such as processing form data, interacting with a database, and creating graphics.

What Does PHP Do?

PHP can be used in two primary ways:

Server-side scripting

PHP was originally designed to create dynamic web content, and it is still best suited for that task. To generate HTML, you need the PHP parser and a web server through which to send the coded document files. PHP has also become popular for generating dynamic content via database connections, XML documents, graphics, PDF files, and so much more.

Command-line scripting

PHP can run scripts from the command line, much like Perl, awk, or the Unix shell. You might use the command-line scripts for system administration tasks, such as backup and log parsing; even some CRON job type scripts can be done this way (as non-visual PHP tasks).

In this book, however, we concentrate on the first item: using PHP to develop dynamic web content.

PHP runs on all major operating systems, from Unix variants including Linux, FreeBSD, Ubuntu, Debian, and Solaris to Windows and Mac OS X. It can be used with all leading web servers, including Apache, Nginx, OpenBSD servers to name a few; even cloud environments like Asure and Amazon are on the rise.

The language itself is extremely flexible. For example, you aren’t limited to outputting just HTML or other text files—any document format can be generated. PHP has built-in support for generating PDF files, GIF, JPEG, and PNG images.

One of PHP’s most significant features is its wide-ranging support for databases. PHP supports all major databases (including MySQL, PostgreSQL, Oracle, Sybase, MS-SQL, DB2, and ODBC-compliant databases), and even many obscure ones. Even the more recent NoSQL-style databases like SQLite and MongoDB are also supported. With PHP, creating web pages with dynamic content from a database is remarkably simple.

Finally, PHP provides a library of PHP code to perform common tasks, such as database abstraction, error handling, and so on, with the PHP Extension and Application Repository (PEAR). PEAR is a framework and distribution system for reusable PHP components. You can find out more about it here (http://pear.php.net).

A Brief History of PHP

Rasmus Lerdorf first conceived of PHP in 1994, but the PHP that people use today is quite different from the initial version. To understand how PHP got where it is today, it is useful to know the historical evolution of the language. Here’s that story, with ample comments and emails from Rasmus himself.

The Evolution of PHP

Here is the PHP 1.0 announcement that was posted to the Usenet newsgroup comp.infosystems.www.authoring.cgi in June 1995:

    From: rasmus@io.org (Rasmus Lerdorf)
    Subject: Announce: Personal Home Page Tools (PHP Tools)
    Date: 1995/06/08
    Message-ID: <3r7pgp$aa1@ionews.io.org>#1/1
    organization: none
    newsgroups: comp.infosystems.www.authoring.cgi
    Announcing the Personal Home Page Tools (PHP Tools) version 1.0.
    These tools are a set of small tight cgi binaries written in C.
    They perform a number of functions including:
    . Logging accesses to your pages in your own private log files
    . Real-time viewing of log information
    . Providing a nice interface to this log information
    . Displaying last access information right on your pages
    . Full daily and total access counters
    . Banning access to users based on their domain
    . Password protecting pages based on users' domains
    . Tracking accesses ** based on users' e-mail addresses **
    . Tracking referring URL's - HTTP_REFERER support
    . Performing server-side includes without needing server support for it
    . Ability to not log accesses from certain domains (ie. your own)
    . Easily create and display forms
    . Ability to use form information in following documents
    Here is what you don't need to use these tools:
    . You do not need root access - install in your ~/public_html dir
    . You do not need server-side includes enabled in your server
    . You do not need access to Perl or Tcl or any other script interpreter
    . You do not need access to the httpd log files
    The only requirement for these tools to work is that you have
    the ability to execute your own cgi programs.  Ask your system
    administrator if you are not sure what this means.
    The tools also allow you to implement a guestbook or any other
    form that needs to write information and display it to users
    later in about 2 minutes.
    The tools are in the public domain distributed under the GNU
    Public License.  Yes, that means they are free!
    For a complete demonstration of these tools, point your browser
    at: http://www.io.org/~rasmus
    Rasmus Lerdorf

Note that the URL and email address shown in this message are long gone. The language of this announcement reflects the concerns that people had at the time, such as password-protecting pages, easily creating forms, and accessing form data on subsequent pages. The announcement also illustrates PHP’s initial positioning as a framework for a number of useful tools.

The announcement talks only about the tools that came with PHP, but behind the scenes the goal was to create a framework to make it easy to extend PHP and add more tools. The business logic for these add-ons was written in C; a simple parser picked tags out of the HTML and called the various C functions. It was never really part of the plan to create a scripting language.

So what happened?

Rasmus started working on a rather large project for the University of Toronto that needed a tool to pull together data from various places and present a nice web-based administration interface. Of course, he used PHP for the task, but for performance reasons, the various small tools of PHP 1.0 had to be brought together better and integrated into the web server.

Initially, some hacks to the NCSA web server were made, to patch it to support the core PHP functionality. The problem with this approach was that as a user, you had to replace your web server software with this special, hacked-up version. Fortunately, Apache was also starting to gain momentum around this time, and the Apache API made it easier to add functionality like PHP to the server.

Over the next year or so, a lot was done and the focus changed quite a bit. Here’s the PHP 2.0 (PHP/FI) announcement that was sent out in April 1996:

    From: rasmus@madhaus.utcs.utoronto.ca (Rasmus Lerdorf)
    Subject: ANNOUNCE: PHP/FI Server-side HTML-Embedded Scripting Language
    Date: 1996/04/16
    Newsgroups: comp.infosystems.www.authoring.cgi
    PHP/FI is a server-side HTML embedded scripting language.  It has built-in
    access logging and access restriction features and also support for
    embedded SQL queries to mSQL and/or Postgres95 backend databases.
    It is most likely the fastest and simplest tool available for creating
    database-enabled web sites.
    It will work with any UNIX-based web server on every UNIX flavour out
    there.  The package is completely free of charge for all uses including
    Feature List:
    . Access Logging
      Log every hit to your pages in either a dbm or an mSQL database.
      Having hit information in a database format makes later analysis easier.
    . Access Restriction
      Password protect your pages, or restrict access based on the refering URL
      plus many other options.
    . mSQL Support
      Embed mSQL queries right in your HTML source files
    . Postgres95 Support
      Embed Postgres95 queries right in your HTML source files
    . DBM Support
      DB, DBM, NDBM and GDBM are all supported
    . RFC-1867 File Upload Support
      Create file upload forms
    . Variables, Arrays, Associative Arrays
    . User-Defined Functions with static variables + recursion
    . Conditionals and While loops
      Writing conditional dynamic web pages could not be easier than with
      the PHP/FI conditionals and looping support
    . Extended Regular Expressions
      Powerful string manipulation support through full regexp support
    . Raw HTTP Header Control
      Lets you send customized HTTP headers to the browser for advanced
      features such as cookies.
    . Dynamic GIF Image Creation
      Thomas Boutell's GD library is supported through an easy-to-use set of
    It can be downloaded from the File Archive at: <URL:http://www.vex.net/php>
    Rasmus Lerdorf

This was the first time the term “scripting language” was used. PHP 1.0’s simplistic tag-replacement code was replaced with a parser that could handle a more sophisticated embedded tag language. By today’s standards, the tag language wasn’t particularly sophisticated, but compared to PHP 1.0 it certainly was.

The main reason for this change was that few people who used PHP 1.0 were actually interested in using the C-based framework for creating add-ons. Most users were much more interested in being able to embed logic directly in their web pages for creating conditional HTML, custom tags, and other such features. PHP 1.0 users were constantly requesting the ability to add the hit-tracking footer or send different HTML blocks conditionally. This led to the creation of an if tag. Once you have if, you need else as well, and from there it’s a slippery slope to the point where, whether you want to or not, you end up writing an entire scripting language.

By mid-1997, PHP version 2.0 had grown quite a bit and had attracted a lot of users, but there were still some stability problems with the underlying parsing engine. The project was also still mostly a one-man effort, with a few contributions here and there. At this point, Zeev Suraski and Andi Gutmans in Tel Aviv, Israel, volunteered to rewrite the underlying parsing engine, and we agreed to make their rewrite the base for PHP version 3.0. Other people also volunteered to work on other parts of PHP, and the project changed from a one-person effort with a few contributors to a true open source project with many developers around the world.

Here is the PHP 3.0 announcement from June 1998:

    June 6, 1998 -- The PHP Development Team announced the release of PHP 3.0,
    the latest release of the server-side scripting solution already in use on
    over 70,000 World Wide Web sites.
    This all-new version of the popular scripting language includes support
    for all major operating systems (Windows 95/NT, most versions of Unix,
    and Macintosh) and web servers (including Apache, Netscape servers,
    WebSite Pro, and Microsoft Internet Information Server).
    PHP 3.0 also supports a wide range of databases, including Oracle, Sybase, Solid,
    MySQ, mSQL, and PostgreSQL, as well as ODBC data sources.
    New features include persistent database connections, support for the
    SNMP and IMAP protocols, and a revamped C API for extending the language
    with new features.
    "PHP is a very programmer-friendly scripting language suitable for
    people with little or no programming experience as well as the
    seasoned web developer who needs to get things done quickly.  The
    best thing about PHP is that you get results quickly," said
    Rasmus Lerdorf, one of the developers of the language.
    "Version 3 provides a much more powerful, reliable, and efficient
    implementation of the language, while maintaining the ease of use and
    rapid development that were the key to PHP's success in the past,"
    added Andi Gutmans, one of the implementors of the new language core.
    "At Circle Net we have found PHP to be the most robust platform for
    rapid web-based application development available today," said Troy
    Cobb, Chief Technology Officer at Circle Net, Inc.  "Our use of PHP
    has cut our development time in half, and more than doubled our client
    satisfaction.  PHP has enabled us to provide database-driven dynamic
    solutions which perform at phenomenal speeds."
    PHP 3.0 is available for free download in source form and binaries for
    several platforms at http://www.php.net/.
    The PHP Development Team is an international group of programmers who
    lead the open development of PHP and related projects.
    For more information, the PHP Development Team can be contacted at

After the release of PHP 3.0, usage really started to take off. Version 4.0 was prompted by a number of developers who were interested in making some fundamental changes to the architecture of PHP. These changes included abstracting the layer between the language and the web server, adding a thread-safety mechanism, and adding a more advanced, two-stage parse/execute tag-parsing system. This new parser, primarily written by Zeev and Andi, was named the Zend engine. After a lot of work by a lot of developers, PHP 4.0 was released on May 22, 2000.

As this book goes to press, PHP version 7.3 has been released for some time. There have already been a few minor “dot” releases, and the stability of this current version is quite high. As you will see in this book, there have been some major advances made in this version of PHP primarily in code processing on the server side. Many other minor changes, function additions, and feature enhancements have also been incorporated.

The Widespread Use of PHP

Figure 1-1 shows the usage of PHP as collected by W3Techs (http://bit.ly/XjyVZM) as of March 2019. The most interesting portion of data here is that 79% of usage on all the surveyed websites and yet version 5.0 is still the most widely used. If you look at the methodology used in their surveys (https://w3techs.com/technologies), you will see that they select the top 10 million sites (based on traffic; website popularity) in the world. As is evident, PHP has a very broad adoption indeed!

Figure 1-1. PHP usage as of March 2019

Installing PHP

As was mentioned above, PHP is available for many operating systems and platforms. Therefore, you are encouraged to go to this URL (http://php.net/manual/install.php) to find the environment that most closely fits the one you will be using and follow the appropriate setup instructions.

From time to time, you may also want to change the way PHP is configured. To do that you will have to change the PHP configuration file and restart your web (Apache) server. Each time you make a change to PHP’s environment, you will have to restart the web (Apache) server in order for those changes to take effect.

PHP’s configuration settings are usually maintained in a file called php.ini. The settings in this file control the behavior of PHP features, such as session handling and form processing. Later chapters refer to some of the php.ini options, but in general the code in this book does not require a customized configuration. See http://php.net/manual/configuration.file.php for more information on php.ini configuration.

A Walk Through PHP

PHP pages are generally HTML pages with PHP commands embedded in them. This is in contrast to many other dynamic web page solutions, which are scripts that generate HTML. The web server processes the PHP commands and sends their output (and any HTML from the file) to the browser. Example 1-1 shows a complete PHP page.

Example 1-1. hello_world.php
    <title>Look Out World</title>
    <?php echo "Hello, world!"; ?>

Save the contents of Example 1-1 to a file, hello_world.php, and point your browser to it. The results appear in Figure 1-2.

Figure 1-2. Output of hello_world.php

The PHP echo command produces output (the string “Hello, world!” in this case) inserted into the HTML file. In this example, the PHP code is placed between the <?php and ?> tags. There are other ways to tag your PHP code—see Chapter 2 for a full description.

Configuration Page

The PHP function phpinfo() creates an HTML page full of information on how PHP was installed and is currently configured. You can use it to see whether you have particular extensions installed, or whether the php.ini file has been customized. Example 1-2 is a complete page that displays the phpinfo() page.

Example 1-2. Using phpinfo()
<?php phpinfo();?>

Figure 1-3 shows the first part of the output of Example 1-2.

Figure 1-3. Partial output of phpinfo()


Example 1-3 creates and processes a form. When the user submits the form, the information typed into the name field is sent back to this page via the $_SERVER[‘PHP_SELF’] form action. The PHP code tests for a name field and displays a greeting if it finds one.

Example 1-3. Processing a form (form.php)
    <title>Personalized Greeting Form</title>
    <?php if(!empty($_POST['name'])) {
      echo "Greetings, {$_POST['name']}, and welcome.";
    } ?>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
      Enter your name: <input type="text" name="name" />
      <input type="submit" />

The form and the message are shown in Figure 1-4.

Figure 1-4. Form and greeting page

PHP programs access form values primarily through the $_POST and $_GET array variables. Chapter 8 discusses forms and form processing in more detail.


PHP supports all the popular database systems, including MySQL, PostgreSQL, Oracle, Sybase, SQLite, and ODBC-compliant databases. Figure 1-5 shows part of a MySQL database query run through a PHP script showing the results of a book search on a book review site. This is showing the book title, the year the book was published, and the book’s ISBN number.


The SQL code for this sample database is in the provided files called library.sql. You can drop this into MySQL after you create the library database, and have the sample database at your disposal for testing out the following code sample as well as the related samples in Chapter 9.

The code in Example 1-4 connects to the database, issues a query to retrieve all available books (with the WHERE clause), and produces a table as output for all returned results through a while loop.

Figure 1-5. A MySQL book list query run through a PHP script
Example 1-4. Querying the Books database (booklist.php)
$db = new mysqli("localhost", "petermac", "password", "library");
// make sure the above credentials are correct for your environment
if ($db->connect_error) {
  die("Connect Error ({$db->connect_errno}) {$db->connect_error}");
$sql = "SELECT * FROM books WHERE available = 1 ORDER BY title";
$result = $db->query($sql);
<table cellSpacing="2" cellPadding="6" align="center" border="1">
    <td colspan="4">
      <h3 align="center">These Books are currently available</h3>
    <td align="center">Title</td>
    <td align="center">Year Published</td>
    <td align="center">ISBN</td>
  <?php while ($row = $result->fetch_assoc()) { ?>
      <td><?php echo stripslashes($row['title']); ?></td>
      <td align="center"><?php echo $row['pub_year']; ?></td>
      <td><?php echo $row['ISBN']; ?></td>
  <?php } ?>

Database-provided dynamic content drives the news, blog, and ecommerce sites at the heart of the Web. More details on accessing databases from PHP are given in Chapter 9.


With PHP, you can easily create and manipulate images using the GD extension. Example 1-5 provides a text-entry field that lets the user specify the text for a button. It takes an empty button image file, and on it centers the text passed as the GET parameter 'message'. The result is then sent back to the browser as a PNG image.

Example 1-5. Dynamic buttons (graphic_example.php)
if (isset($_GET['message'])) {
  // load font and image, calculate width of text
  $font = dirname(__FILE__) . '/fonts/blazed.ttf';
  $size = 12;
  $image = imagecreatefrompng("button.png");
  $tsize = imagettfbbox($size, 0, $font, $_GET['message']);

  // center
  $dx = abs($tsize[2] - $tsize[0]);
  $dy = abs($tsize[5] - $tsize[3]);
  $x = (imagesx($image) - $dx) / 2;
  $y = (imagesy($image) - $dy) / 2 + $dy;

  // draw text
  $black = imagecolorallocate($im,0,0,0);
  imagettftext($image, $size, 0, $x, $y, $black, $font, $_GET['message']);

  // return image
  header("Content-type: image/png");

} ?>
    <title>Button Form</title>

    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="GET">
      Enter message to appear on button:
      <input type="text" name="message" /><br />
      <input type="submit" value="Create Button" />

The form generated by Example 1-5 is shown in Figure 1-6. The button created is shown in Figure 1-7.

You can use GD to dynamically resize images, produce graphs, and much more. PHP also has several extensions to generate documents in Adobe’s popular PDF format. Chapter 10 covers dynamic image generation in depth, while Chapter 11 provides instruction on how to create Adobe PDF files.

Figure 1-6. Button creation form
Figure 1-7. Button created

What’s Next

Now that you’ve had a taste of what is possible with PHP, you are ready to learn how to program in PHP. We start with the basic structure of the language, with special focus given to user-defined functions, string manipulation, and object-oriented programming. Then we move to specific application areas such as the Web, databases, graphics, XML, and security. We finish with quick references to the built-in functions and extensions. Master these chapters, and you will have mastered PHP!

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required