PHP on Apache: The Definitive Installation Guide

PHP on Apache: The Definitive Installation Guide


August 9, 2000

The technology that supports the Web continues to evolve, and one of the latest mutations involves capitalising on its very user-driven interactivity. The days of all-static content are past; the Web has evolved to a point at which many sites actually remember personal preferences for each of their (potentially millions) of visitors. News sites may display stories in only those categories you find interesting; online music stores can provide you with listings of new works sorted in order by your favourite artists; Web search engines can learn to implicitly restrict the types of content they'll list for you. The possibilities are endless, and the key is generating a unique presentation for each viewer.

There are a number of ways of accomplishing this, from the primitive fly-swatter capabilities provided by "server-side includes" to the tactical nuke Extra Strength features found in application servers. The PHP scripting language falls somewhere into the middle ground, supplying phenomenal capabilities for free.

What is PHP?

PHP is a scripting language, with a particular affinity for and emphasis on enhancing Web pages. It has a syntax very similar to C (with a smattering of Perl and shell), and includes lots and lots of functions for things like database access, dealing with CGI requests, and image creation and manipulation.

When PHP is used as an Apache module, and the language elements are embedded in the document pages themselves, the HTML file might look something like the following:

    <head>
     <?
         //
	 // Preload all the functions and other definitions we need.
	 //
	 include("/scripts/definitions.php3");
	  = lookup_visitor();
	 echo "  <title>WhizBang Products: Welcome back, "
	     . ["first_name"] . "!</title>\n";
     ?>
    </head>
    <body bgcolor="#ffffff">

     <h1 align="center">Super-Duper Whizbang Products</h1>
     <h2 align="center">Welcome back,
      <? echo ["first_name"] . " "
             . ["last_name"]; ?></h2>

When a Web client requests a PHP-enabled page, the mod_php module gets to interpret the document and make changes to it before the Web server itself sends the results back. The results of the above PHP fragments might cause the following to be what the Web client actually receives:

    <head>
     <title>WhizBang Products: Welcome back, Ken!<title>
    </head>
    <body bgcolor="#ffffff">
     <h1 align="center">Super-Duper Whizbang Products</h1>
     <h2 align="center">Welcome back, Ken Coar</h2>

Notice how all the stuff between "<?" and "?>" was replaced—interpreted by mod_php—before it reached the browser? That's part of the power of PHP.

Assumptions in this Article

It's a good idea to maintain the PHP source in a different directory from your Apache source tree; since they're from separate projects, maintaining the separation in where the software lives avoids confusion. For the rest of this article, I'm going to make the following assumptions:

  1. your Apache source tree starts at ./apache-1.3/
  2. your Apache ServerRoot is /usr/local/web/apache
  3. your PHP source tree starts at ./php/php3/

All of the cd and other shell commands in this article that refer to directories use these locations.

Since you'll need to compile the PHP software yourself (few binaries are readily available, and those are feature-limited and built with very few extensons), and since it's an Apache module, you need to have the complete Apache source tree available. If you install the Apache software using a package provided as part of your Linux distribution, it's possible you won't have the source tree, so you'll need to download it and unpack it. See the "Building Apache at Lightspeed" appendix at the end of this article.

How to Get PHP

PHP is open-source software, which means (among other things) that there are source code as well as binary versions available. As with a lot of open-source software, development on PHP is rapid enough that any attempt to put it on a CD or otherwise package it on a long-term distribution medium suffers from the "instantly stale" syndrome.

In other words, the place to get the PHP software is the Internet itself. There are multiple Web sites devoted to the PHP project, but the main one is http://www.php.net/, and most of the others are reachable from there.

There are two ways of keeping up with the PHP project as its development continues:

  • Periodically download a tarball of a packaged release, or
  • Keep up with the very latest developments by keeping a synchronised copy of the master sources

In order to use PHP, you're going to need to build it, which means being familiar with the usual software development tools: a shell, tar, compiling, make, and so on.

The currently stable version of PHP is version 3. Its successor, version 4, is currently under development and there have been a few beta releases already. However, the version used in this column is the more wide-spread V3, and the instructions are specific to that version; they may or may not work with V4.

Getting the Most Recent Release

If you're afraid of warts and glitches that might lurk in the latest development version, updating only when a stable release is made is probably best. Of course, there are disadvantages inherent in playing it safe--such as not getting the latest bug fixes or feature additions, or the added pain of having to build the new version in a separate directory tree and then switch over from the old one to the new.

The easiest way to download a release tarball to your Linux system is to use a Web browser running on that system and visit http://www.php.net/downloads.php3, choose the appropriate package and save it. (It's not readily available in any other way; for instance, it's not accessible from the PHP site using FTP.)

Keeping Up with the Bleeding Edge

To really keep up with the very latest bug fixes (and bugs) in the latest development version, you'll need to have access to the Internet, a CVS client, and some development tools like autoconf, automake, and bison. Just download the latest revision of all of the sources (the latest version is called the "HEAD") into your working directory, and then build it as though it was extracted it from a release tarball. The following shows how:


    % cvs -d :pserver:cvsread@cvs.php.net:/repository login
    (Logging in to cvsread@cvs.php.net)
    CVS password:   use "phpfi" as the password
    % cd ./php
    % cvs -d :pserver:cvsread@cvs.php.net:/repository checkout php3

This will extract the latest versions of everything into the tree starting at ./php/php3/. The command will display lots of information about what it's doing, which can be ignored (except for error messages, of course!). In order to keep in sync with the latest changes being made to the master repository, just repeat the last two commands every few days.

Since this method involves grabbing the sources themselves rather than a prepared package, take at least this one extra step before you build: run autoconf in order to generate the ./php/php3/configure script. This is simple:

    % cd ./php/php3/
    % ./buildconf
    % autoconf

and you're ready to build.

To follow this path, subscribe to the php-dev mailing list to keep up to date with changes (like the addition of the buildconf step above, which is quite recent—and necessary; PHP won't build without it!). Find out more about the PHP mailing lists at http://www.php.net/support.php3.

PHP Extensions

The PHP package is just brimful of capabilities that you can enable if you have the appropriate extra pieces installed on your system. For instance, one of PHP's strong points is its simple and easy interface to numerous different database system such as Oracle, MySQL, mSQL, DB2, and so on.

You enable these extensions by letting the ./php/php3/configure script know about them when you invoke it. For example, if you want to be able to use MySQL and XML within your PHP scripts (or PHP pages), you might invoke it as

    % ./configure --with-mysql --with-xml

To see a list of the extensions that PHP can support, invoke the script as


    % ./configure --help

Building PHP for CGI Use

Like Perl, PHP can be used in standalone scripts as well as embedded in Web pages. Unfortunately, to do both you will need to build it twice: once for each type of use. (Version 4 of PHP supposedly allows a single build to provide both the standalone script engine and the Apache module.)

Building the PHP script interpreter is very simple:

    % cd ./php/php3/
    % rm -f config.status config.cache
    % make clean
    % ./configure --enable-discard-path other-options
    % make
    % make install

(Performing the make install step requires write access to the /usr/local/bin directory, so you may need to execute it as root.)

The --enable-discard-path switch on the ./configure invocation is necessary to use PHP scripts as CGI scripts under a Web server, such as in the cgi-bin directory. To just invoke PHP scripts directly from shell command lines, you can omit it. Of course, it does no harm to include it, so you might as well.

Building PHP as an Apache Module

To use embedded PHP code in Web pages, build it in one of two different ways, depending upon whether it is to be loaded dynamically or built permanently into the Apache server. The only difference between the interpreter and dynamic module builds is the configure command; the sequence for building it as a static module is considerably more complex.

In order to allow Apache to recognise PHP-enabled HTML files as being grist for mod_php's mill requires a line like the following in the /usr/local/web/apache/conf/httpd.conf file:

   AddType application/x-httpd-php3 .php3

Then the Web server will know to invoke the PHP module to process the file.

Linking it Statically

Static modules are linked into the Apache server itself, and cannot be removed without recompiling. This means that they can consume resources, such as memory, even if not used or activated. It also means rebuilding the entire server any time a single module is altered (such as upgrading the PHP installation). The Apache Group now strongly encourages the use of DSOs (dynamic shared objects) in preference to static modules because of their flexibility. While static modules are far from deprecated, I'm including the steps here only for completeness; Linux has no problem with dynamic modules—use the dynamic-module method instead of the static.

In order to build mod_php for static inclusion in the Apache server it's necessary to jump back and forth between the Apache and PHP directories, following a series of interdependent configuration and compilation steps. You indicate that you're building mod_php statically by using the --with-apache switch on the ./php/php3/configure script invocation.


    % #
    % # Preconfigure Apache so that PHP knows where things are
    % #
    % cd ./apache-1.3
    % ./configure --prefix=/usr/local/web/apache
    % #
    % # Now configure and build PHP as a module
    % #
    % cd ../php/php3
    % rm -f config.status config.cache
    % ./configure --with-apache=../../apache-1.3 other-switches
    % make
    % make install
    % #
    % # Now *really* configure Apache, and build it
    % #
    % cd ../../apache-1.3
    % ./configure --prefix=/usr/local/web/apache \
    > --activate-module=src/modules/php3/libphp3.a
    % make
    % #
    % # Install the resulting httpd application
    % #
    % /usr/local/web/apache/bin/apachectl stop
    % cp src/httpd /usr/local/web/apache/bin
    % cd ../php/php3
    % cp php3.ini-dist /usr/local/lib/php3.ini
    % /usr/local/web/apache/bin/apachectl start

(You will probably have to execute the last five commands as root.)

See how complicated this is? Repeat for every PHP module rebuild.

Building mod_php as a Dynamically Loaded Object

To build PHP as a dynamic Apache module, build and install the Apache server itself using the APACI method (i.e., with the ./apache-1.3/configure script). This is because the PHP configure script needs to use one of the files that APACI installs.

To build PHP as a dynamic shared object (DSO), use the following sequence of commands:

    % cd ./php/php3/
    % rm -f config.status config.cache
    % make clean
    % ./configure --with-apxs=/usr/local/web/apache/bin/apxs other-options
    % make
    % /usr/local/web/apache/bin/apachectl stop   # shut down Apache entirely
    % make install
    % /usr/local/web/apache/bin/apachectl start  # restart Apache

When that's all done, your Apache server should be capable of handling PHP CGI scripts and PHP-enabled Web pages. And to upgrade just PHP from a new version, just repeat the process--without touching any other part of Apache.

For building PHP on Red Hat Linux 6.1 and using the Apache RPMs, fix a broken file provided by them before executing the above commands. See the "Fixing Red Hat 6.1's apxs Script" appendix in this article for the details.

Testing Your Installation

If you built PHP as a script interpreter, verify that it is working correctly by creating and executing a test script such as the following:


    % cat <<EOP > script-test.php3
    > #!/usr/local/bin/php -q
    > <? echo "PHP script interpreter is OK!\n"; ?>
    > EOP
    % chmod 755 script-test.php3
    % ./script-test.php3
    PHP script interpreter is OK!
    %

The '-q' switch tells the interpreter to suppress the 'Content-type: text/html' line it ordinarily prints by default (because it assumes it's being run as a CGI script).

If PHP was built as an Apache module, the simplest way to test it is to create a file in the DocumentRoot that contains this single line:

    <? phpinfo(); ?>

and then fetch it in a browser. It should display a long and detailed Web page describing the PHP module, the extensions that were included when it was built, and the Apache environment as well.

Going Further

With PHP installed and working, what do you do then? Well, that's really up to you--but for a couple of examples of what's possible, check out the PHP site itself and the ApacheCon 2000 site. The PHP site is totally driven by the software; as you browse through the online documentation, you can see that not only is it 'live,' meaning that you can comment on it or make suggestions for improvements, but you can also see what other people have suggested. The ApacheCon 2000 site uses PHP to display the very latest information on sessions, speakers, sponsors, and other aspects of the conference, building each page when it's requested from the data, stored in a MySQL database.

The documentation link at the PHP site is invaluable. While it doesn't give a lot of guidance on how to accomplish things, it's very complete when it comes to descriptions of the PHP functions. For more, check USENET or the PHP mailing lists.

One final trick, which is illustrated at the PHP site, is to add the 'show me the source' feature to your server. Add a line like this to your /usr/local/web/apache/conf/httpd.conf file:


    AddType application/x-httpd-php3-source .phps

and then soft-link .php3 files to the same name with a .phps extension, as with

    % ln -s some-php-file.php3 some-php-file.phps

Requesting the .phps file in a Web browser will display the source of a PHP (or PHP-enabled HTML) file, nicely color-coded.

In Conclusion

If running the Apache Web server and wanting to make your Web pages more interactive, responsive, personalised or otherwise to "spice them up," PHP is an easy and excellent way to do it. The software is under constant intense scrutiny by dozens of developers, so problems are fixed quite quickly.

Got a Topic You Want Covered?

If you have a particular Apache-related topic that you'd like covered in a future article in this column, please let me know at <coar@Apache.Org>. I do read and answer my email, usually within a few hours (although a few days may pass if I'm travelling or my mail volume is way up). If I don't respond within what seems to be a reasonable amount of time, ping me again!

Appendix A: Building Apache at Lightspeed

To build Apache from source (e.g., your Linux distribution package didn't provide the pieces necessary to add PHP), use the following commands as a quick-start. Download the latest released version of the Apache tarball and unpack it into a working directory. The top-level directory will then be ./apache-1.3, which matches assumption #1 described earlier.

    % cd ./apache-1.3
    % env CC=gcc CFLAGS="-O2 -Wall" \
    > ./configure --enable-shared=max --enable-module=most \
    > --with-layout=Apache --prefix=/usr/local/web/apache \
    > --with-port=80
    Configuring for Apache, Version 1.3.10-dev
     + using installation path layout: Apache (config.layout)
    Creating Makefile

    Creating Configuration.apaci in src
        [more configuration output]
    % make
        [lots of compilation output]
    % make install
        [lots more output describing file placement]
    % /usr/local/web/apache/bin/apachectl start

If there are no errors, you should now have a working Apache installation in the location that matches assumption #2 described earlier. It was written to work with dynamic modules rather than static ones, so build PHP as a dynamic module.

It's far beyond the scope of this article to give any more information about building Apache; it is about PHP, after all. If you'd like to see an article in this column about the details of building Apache, let me know.

Appendix B: Apache Source Components Provided by Linux Distributions

The following table shows the paths to the apxs and Apache source tree as supplied by the packages included with various Linux distributions. Note: Some of this information is inferential only, determined by examining the distribution kits rather than actually installing them. As a result, it may be inaccurate in some respects.

Distribution Version of Apache supplied Value for --with-apxs Value for --with-apache
Caldera OpenLinux 2.3 1.3.4 [note 1]
Corel 1.3.3 /usr/sbin/apxs [note 1]
Debian GNU/Linux 2.1 1.3.3 /usr/sbin/apxs [note 1]
Linux-Mandrake 6.1 1.3.9 /usr/sbin/apxs [note 2] [note 1]
Linux Pro 5.4 1.1.3, 1.2.5 [note 1]
Red Hat Linux 6.1 1.3.9 /usr/sbin/apxs [notes 2, 3] [note 1]
Slackware 7.0 1.3.9 /var/lib/apache/sbin/apxs /var/lib/apache
S.u.S.E. Linux 6.2 1.3.6 /usr/sbin/apxs [note 1]
TurboLinux 3.6 1.3.6 /usr/sbin/apxs [note 2] [note 1]

Notes

  1. The binary packages of this distribution do not include the source elements you need to build version 1.3.6 or later of the Apache Web server. Either install an Apache 1.3 source package from the distribution (if available), or download the Apache source and build it by hand. (See the "Building Apache at Lightspeed" section of this article.)
  2. Install the apache, apache-devel, and freetype-devel packages in order to build PHP with apxs.
  3. There's a problem with the Apache RPMs in Red Hat's 6.1 distribution. See the "Fixing Red Hat 6.1's apxs Script" Appendix for details.

Appendix C: Fixing Red Hat 6.1's apxs Script

The apache-devel RPM included in the original Red Hat 6.1 distribution contains a broken version of the apxs script, which will prevent you from using it with PHP (or any other module). It's possible that a later redistribution of 6.1 (such as CDs made and passed around by a Linux user group) may have this problem fixed—but just in case, check /usr/sbin/apxs. If somewhere near line 81 you see


    my     = 'modules';

then change 'modules' to '/usr/lib/apache'. Next, look for lines that look like this:

    my       = 'gcc';
    my  = q(-shared);

If the lines in your /usr/sbin/apxs script look something like this, and the line has been corrected, you should be in good shape to build PHP. You can find more details in the ./php/php3/INSTALL.REDHAT file included in the PHP distribution.