As seen on LinuxPlanet.Com Adding PHP to Apache on Linux
By: Ken Coar
Copyright © 1999 by Ken Coar. All rights reserved.

Supercharging Your Web Pages

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 can 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 implicitly restrict the types of content they'll display. The possiilities 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("$DOCUMENT_ROOT/scripts/definitions.php3");
	 $pdetails = lookup_visitor();
	 echo "  <title>WhizBang Products: Welcome back, "
	     . $pdetails["first_name"] . "!</title>\n";
     ?>
    </head>
    <body bgcolor="#ffffff">
     <h1 align="center">Super-Duper Whizbang Products</h1>
     <h2 align="center">Welcome back,
      <? echo $pdetails["first_name"] . " "
             . $pdetails["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 Building Apache at Lightspeed at the end of this article.

Downloading PHP

The PHP software is open-source, which means (among other things) that you can get the source code as well as binary versions of it. 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 <URL: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:

In order to use PHP, you're going to need to build it, which means that you need to be 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 <URL:http://www.php.net/downloads.php3>, choose the appropriate package, and save it to your system. (It's not readily available in any other way; for instance, you can't download it from the PHP site with FTP.)

Keeping Up with the Bleeding Edge

If you really want to 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. You just check out 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 you had extracted it from a release tarball. The following shows how you can do this:

    % 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, but you can ignore it (unless you see 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, you'll need to take at least one extra step before you can build: you need to 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.

Note: If you're going to follow this path, you should subscribe to the php-dev mailing list so you can 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!). You can find out more about the PHP mailing lists at <URL: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, if you want 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
  

(In order to perform the make install step, you're going to need 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 if you intend to use PHP scripts as CGI scripts under your Web server, such as in your cgi-bin directory. If you're just going to invoke your 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 do so.

Building PHP as an Apache Module

If you want to use embedded PHP code in your Web pages, you need to build it in one of two different ways, depending upon whether you want to load it dynamically or have it built permanently right into the Apache server. The only difference between the interpreter and dyanmic 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, you need to have a line like the following in your /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 you don't use or activate them. It also means that you have to rebuild the entire server any time you alter a single module (such as upgrading your 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 and you should use the dynamic-module method instead.

In order to build mod_php for static inclusion in the Apache server, you need 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? And you need to repeat it any time you want to rebuild your PHP module.

Building mod_php as a Dynamically-Loaded Object

If you're going to build PHP as a dynamic Apache module, you really need to be building and installing 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.

If you want to build PHP as a dynamic shared object (DSO), you can 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 if you want to upgrade just PHP from a new version, you can just repeat the process -- without having to touch any other part of Apache.

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

Testing Your Installation

If you built PHP as a script interpreter, you can 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 you built PHP as an Apache module, the simplest way to test it is to create a file in your DocumentRoot that contains this single line:

    <? phpinfo(); ?>
  

and then fetch it in your browser. You should get 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

Once you've got PHP installed and working, what do you do then? Well, that's really up to you -- but if you want 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 which are all 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 one of your .php3 files to the same name with a .phps extension, as with

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

Then when you request the .phps file in your Web browser you'll see a display of the source of your PHP (or PHP-enabled HTML) file, nicely colour-coded.

Conclusion

If you're running the Apache Web server and you want to make your Web pages more interactive, responsive, personalised, or otherwise '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.


Appendices

Building Apache at Lightspeed

If you need to build Apache from source (e.g., your Linux distribution package didn't provide the pieces necessary to add PHP), you can use the following commands as a quick-start. You should 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 you didn't encounter any errors, you should now have a working Apache installation in the location that matches assumption #2 described earlier. It's been built to work with dynamic modules rather than static ones, so you should 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.

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. You must 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. You must 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 section below for details.

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 that wants to use it). 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 $CFG_LIBEXECDIR    = 'modules';
     

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

    my $CFG_LD_SHLIB      = 'gcc';
    my $CFG_LDFLAGS_SHLIB = q(-shared);
     

If the lines in your /usr/sbin/apxs script look something like this, and the $CFG_LIBEXECDIR 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.

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; drop me an email 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, feel free to ping me again.

About the Author

Ken Coar is a member of the Apache Group and a director and vice president of the Apache Software Foundation. He is also a core member of the Jikes open-source Java compiler project, a contributor to the PHP project, the author of Apache Server for Dummies, and a contributing author to Apache Server Unleashed. He can be reached via email at <coar@apache.org>.