Installing and Configuring PHP - Getting Up and Running - Sams Teach Yourself PHP, MySQL and Apache All in One (2012)

Sams Teach Yourself PHP, MySQL and Apache All in One (2012)

Part I. Getting Up and Running

Chapter 4. Installing and Configuring PHP

In this chapter, you learn the following:

How to install PHP

How to test your PHP installation

How to find help when things go wrong

The basics of the PHP language

In this chapter, you acquire, install, and configure PHP and make some basic changes to your Apache installation.

Current and Future Versions of PHP

The installation instructions in this chapter refer to PHP version 5.4.0, which is the current version of the software.

The PHP Group uses revisions and minor releases for updates containing security enhancements or bug fixes. These releases do not follow a set release schedule; when enhancements or fixes are added to the code and are thoroughly tested, the PHP Group releases a new version with a new revision number.

It is possible that by the time you purchase this book the minor version number will have changed, to 5.4.1 or beyond. If that is the case, you should read the list of changes at for any installation/configuration process changes. These processes make up the bulk of this chapter.

Although it is unlikely that any installation instructions will change between minor version updates, always check the changelog of software that you install and maintain. If a revision does occur while you are reading this book but the changelog notes no installation changes, just make a mental note and substitute the new version number wherever it appears in the installation instructions and accompanying figures.

Building PHP on Linux/UNIX with Apache

This section examines one way of installing PHP with Apache on Linux/UNIX. The process is more or less the same for any UNIX-like operating system. Although you might be able to find prebuilt versions of PHP for your system, compiling PHP from source gives you greater control over the features built in to your binary.

To download the PHP distribution files, go to the home of PHP,, and follow the link to the Downloads section. Grab the latest version of the source code—for this example, we are using 5.4.0. Your distribution will be named something similar to php-VERSION.tar.gz, where VERSION is the most recent release number. This archive will be a compressed tar file, so you need to unpack it:

# gunzip < php-VERSION.tar.gz | tar xvf -

Keep the downloaded file in a directory reserved for source files, such as /usr/src/ or /usr/local/src/. After your distribution is unpacked, you should move to the PHP distribution directory:

# cd php-VERSION

In your distribution directory, you will find a script called configure. This script accepts additional information that is provided when the configure script is run from the command line. These command-line arguments control the features that PHP supports. This example includes the basic options you need to install PHP with Apache and MySQL support. We discuss some of the available configure options later in the chapter and throughout the book as they become relevant.

# ./configure --prefix=/usr/local/php \
--with-mysqli=/usr/local/mysql/bin/mysql_config \


If you have installed MySQL or Apache in a different location than the paths indicated in the configuration shown here, ensure that you substitute the appropriate directory paths in the command.

After the configure script has run, you are returned to the prompt. For example:

Generating files
updating cache ./config.cache
creating ./config.status
creating php5.spec
creating main/build-defs.h
creating scripts/phpize
creating scripts/man1/phpize.1
creating scripts/php-config
creating scripts/man1/php-config.1
creating sapi/cli/php.1
creating main/php_config.h
creating main/internal_functions.c
creating main/internal_functions_cli.c
| License: |
| This software is subject to the PHP License, available in this |
| distribution in the file LICENSE. By continuing this installation |
| process, you are bound by the terms of this license agreement. |
| If you do not agree with the terms of this license, you must abort |
| the installation process at this point. |

Thank you for using PHP.


From the prompt, issue the make command, followed by the make install command. These commands should end the process of PHP compilation and installation and return you to your prompt:

chmod 755 /usr/local/apache2/modules/
[activating module 'php5' in /usr/local/apache2/conf/httpd.conf]
Installing PHP CLI binary: /usr/local/php/bin/
Installing PHP CLI man page: /usr/local/php/php/man/man1/
Installing PHP CGI binary: /usr/local/php/bin/
Installing build environment: /usr/local/php/lib/php/build/
Installing header files: /usr/local/php/include/php/
Installing helper programs: /usr/local/php/bin/
program: phpize
program: php-config
Installing man pages: /usr/local/php/php/man/man1/
page: phpize.1
page: php-config.1

You need to ensure that two very important files are copied to their correct locations. First, issue the following command to copy the development version of php.ini to its default location. You learn more about php.ini later in this chapter:

# cp php.ini-development /usr/local/lib/php.ini

Next, copy the PHP shared object file to its proper place in the Apache installation directory, if it has not already been placed there by the installation process; it usually will be, as you can see in the make install output, just shown:

# cp libs/ /usr/local/apache2/modules/

You should now be able to configure and run Apache, but let’s cover some additional configuration options before heading on to the “Integrating PHP with Apache on Linux/UNIX” section.

Additional Linux/UNIX Configuration Options

In the previous section, when we ran the PHP configure script, we included some command-line arguments that determined some features that the PHP engine will include. The configure script itself gives you a list of available options, including the ones we used. From the PHP distribution directory, type the following:

# ./configure --help

This command produces a long list, so you might want to add it to a file and read it at your leisure:

# ./configure --help > configoptions.txt

If you discover additional functionality you want to add to PHP after you install it, simply run the configuration and build process again. Doing so creates a new version of and places it in the Apache directory structure. All you have to do is restart Apache to load the new file.

Integrating PHP with Apache on Linux/UNIX

To ensure that PHP and Apache get along with one another, you need to check for—and potentially add—a few items to the httpd.conf configuration file. First, look for a line like the following:

LoadModule php5_module modules/

If this line is not present or only appears with a pound sign (#) at the beginning of the line, you must add the line or remove the #. This line tells Apache to use the PHP shared object file created by the PHP build process (

Next, look for this section:

# AddType allows you to add to or override the MIME configuration
# file mime.types for specific file types.

Add the following line to that section:

AddType application/x-httpd-php .php

This statement ensures that the PHP engine will parse files that end with the .php extension. Your selection of filenames might differ; you might want to parse all files ending with *.html as PHP, for example.

Save this file and then restart Apache. When you look in your error_log, you should see something like the following line:

[Tue Mar 13 10:42:47 2012] [notice] Apache/2.4.1 (Unix) PHP/5.4.0 configured

PHP is now part of the Apache web server. If you want to learn how to install PHP on a Mac OS X or Windows platforms, keep reading. Otherwise, you can skip ahead to the “Testing Your Installation” section.

Installing PHP on Mac OS X

There are a few different options for installing PHP with Apache on Mac OS X, including building from source as described in the previous section. Some users may find the simplest method is to install PHP from a precompiled binary package, such as those from MacPorts (at or as part of the all-in-one installation packages from XAMPP (as shown in Chapter 1, “Installation QuickStart Guide with XAMPP”) or MAMP (at However, if you are comfortable with the command line, I recommend following the instructions in the previous section, “Building PHP on Linux/UNIX with Apache.”

Installing PHP on Windows

Installing PHP on Windows requires nothing more than downloading the distribution file. To download the PHP distribution files, go to the home of PHP on Windows,, and follow the link to the Downloads page. Grab the latest version of the thread-safe ZIP package—for this example, we are using 5.4.0. Your distribution will be named something similar to, where VERSION is the most recent release number.

After the file downloads to your system, double-click it to launch your unzipping software. The distribution is packed up with relative pathnames already in place, so extract the files to a new directory called C:\php\, where it will place all the files and subdirectories under that new directory.

Next, go to the C:\php\ directory and copy the php.ini-development file to php.ini. Now, to get a basic version of PHP working with Apache, you need to make a few minor modifications to the Apache configuration file.


On some Windows systems you might need to set an explicit environment variable in order for PHP to run correctly; setting it will not cause any harm so even if you are unsure if it is necessary, there’s no reason not to. For information on adding the PHP directory to the PATH environment variable, see the entry in the PHP FAQ at

Integrating PHP with Apache on Windows

To ensure that PHP and Apache get along with one another, you need to add a few items to the httpd.conf configuration file. First, find a section that looks like this:

# Example:
# LoadModule foo_module modules/
LoadModule access_module modules/
#LoadModule vhost_alias_module modules/

At the end of this section, add the following:

LoadModule php5_module C:/php/php5apache2_2.dll

In addition, add the following to ensure Apache knows where php.ini resides:

PHPIniDir "C:/php/"

Next, look for this section:

# AddType allows you to add to or override the MIME configuration
# file mime.types for specific file types.

Add the following line:

AddType application/x-httpd-php .php

This statement ensures that the PHP engine will parse files that end with the .php extension. Your selection of filenames might differ; for example, you might want to parse all *.html files as PHP files.

Save the httpd.conf file and then restart Apache. The server should start without warning; PHP is now part of the Apache web server.

php.ini Basics

After you have compiled or installed PHP, you can still change its behavior with the php.ini file. On Linux/UNIX systems, the default location for this file is /usr/local/php/lib or the lib subdirectory of the PHP installation location you used at configuration time. On a Windows system, this file should be in the PHP directory or another directory as specified by the value of PHPIniDir in the Apache httpd.conf file.

Directives in the php.ini file come in two forms: values and flags. Value directives take the form of a directive name and a value separated by an equal sign. Possible values vary from directive to directive. Flag directives take the form of a directive name and a positive or negative term separated by an equal sign. Positive terms include 1, On, Yes, and True. Negative terms include 0, Off, No, and False. Whitespace is ignored.


On Windows systems, it is important to explicitly provide the value for the extension_dir directive. If you installed PHP in C:\php then the value of extension_dir should be "C:\php\ext".

You can change your php.ini settings at any time, but after you do, you need to restart the server for the changes to take effect. At some point, take time to read through the php.ini file on your own to see the types of things that you can configure.

Testing Your Installation

The simplest way to test your PHP installation is to create a small test script that uses the phpinfo() function. This function produces a long list of configuration information. Open a text editor and type the following line:

<?php phpinfo(); ?>

Save this file as phpinfo.php and place it in the document root of your web server—the htdocs subdirectory of your Apache installation or the /Library/WebServer/Documents directory on Mac OS X. Access this file using your web browser, and you should see something like what is shown inFigure 4.1.


Figure 4.1 The results of phpinfo().

The exact output of phpinfo() depends on your operating system, PHP version, and configuration options.

Getting Installation Help

Help is always at hand on the Internet, particularly for problems concerning open source software. Wait a moment before you click the Send button, however. No matter how intractable your installation, configuration, or programming problem might seem, chances are you are not alone. Someone has probably already answered your question.

When you hit a brick wall, your first recourse should be to the official PHP site at (particularly the annotated manual at If you still cannot find your answer, don’t forget that the PHP site is searchable. The advice you are seeking may be lurking in a press release or a FAQ file. You can also search the mailing list archives at These archives represent a huge information resource with contributions from many of the great minds in the PHP community. Spend some time trying out a few keyword combinations.

If you are still convinced that your problem has not been addressed, you might well be doing the PHP community a service by exposing it. You can join the PHP mailing lists at Although these lists often have high volume, you can learn a lot from them. If you are serious about PHP scripting, you should certainly subscribe to at least a digest list. After you’ve subscribed to the list that matches your concerns, consider posting your problem.

When you post a question, it is a good idea to include as much information as possible (without writing a novel). The following items are often pertinent:

• Your operating system

• The version of PHP you are running or installing

• The configuration options you chose

• Any output from the configure or make commands that preceded an installation failure

• A reasonably complete example of the code that is causing problems

Why all these cautions about posting a question to a mailing list? First, developing research skills will stand you in good stead. A good researcher can generally solve a problem quickly and efficiently. Posting a naive question to a technical list often results in a wait rewarded only by a message or two referring you to the archives where you should have begun your search for answers in the first place.

Second, remember that a mailing list is not analogous to a technical support call center. No one is paid to answer your questions. Despite this, you have access to an impressive pool of talent and knowledge, including that of some of the creators of PHP itself. A good question and its answer will be archived to help other coders. Asking a question that has already been answered several times just adds more noise.

Having said this, don’t be afraid to post a problem to the list. PHP developers are a civilized and helpful breed, and by bringing a problem to the attention of the community, you might be helping others to solve the same problem.

The Basics of PHP Scripts

Let’s jump straight in with a PHP script. To begin, open your favorite text editor. Like HTML documents, PHP files are made up of plain text. You can create them with any text editor, and most popular HTML editors and programming IDEs (integrated development environments) provide support for PHP.


A good website for finding PHP-friendly editors is at

Type in the example in Listing 4.1 and save the file to the document root of your web server, using a name something like first.php.

Listing 4.1 A Simple PHP Script

1: <?php
2: echo "<h1>Hello Web!</h1>";
3: ?>

If you are not working directly on the machine that will be serving your PHP script, you need to use a File Transfer Protocol (FTP) or Secure Copy (SCP) client to upload your saved document to the server. When the document is in place on the server, you should be able to access it using your browser. If all has gone well, you should see the script’s output. Figure 4.2 shows the output from the first.php script.


Figure 4.2 Success: the output from first.php.

Beginning and Ending a Block of PHP Statements

When writing PHP, you need to inform the PHP engine that you want it to execute your commands. If you don’t do this, the code you write will be mistaken for HTML and will be output to the browser. You can designate your code as PHP with special tags that mark the beginning and end of PHP code blocks. Table 4.1 shows four such PHP delimiter tags.

Table 4.1 PHP Start and End Tags


Of the tags in Table 4.1, only the standard and script tags are guaranteed to work on any configuration. You must explicitly enable the short and ASP-style tags in your php.ini file.

To activate recognition for short tags, you must make sure that the short_open_tag switch is set to On in php.ini:

short_open_tag = On;

To activate recognition for the ASP-style tags, you must enable the asp_tags setting in php.ini:

asp_tags = On;


To ensure portable, reusable code, it is best to use the standard tags rather than short tags or ASP-style tags for the simple reason that server configurations are unique—use the standard style because you know you can count on it as part of any configuration.

After you have edited php.ini and restarted Apache, you should be able to use any of the four styles in your scripts. This is largely a matter of preference, although if you intend to include XML in your script, you should disable the short tags (<? ?>) and work with the standard tags (<?php ?>).


The character sequence <? tells an XML parser to expect a processing instruction and is therefore often included in XML documents. If you include XML in your script and have short tags enabled, the PHP engine is likely to confuse XML processing instructions and PHP start tags. Disable short tags if you intend to incorporate XML in your document.

Let’s run through some of the ways in which you can legally write the code in Listing 4.1. Given the configuration changes shown earlier, you can use any of the four PHP start and end tags that you have seen:

echo "Hello Web!";

echo "Hello Web!";

echo "Hello Web!";

<script language="php">
echo "Hello Web!";

You can also put single lines of code in PHP on the same line as the PHP start and end tags:

<?php echo "Hello Web!"; ?>

Now that you know how to define a block of PHP code, let’s take a closer look at the code in Listing 4.1 itself.

The echo and print() Statements

Simply put, you can use the echo statement to output data. In most cases, anything output by echo ends up viewable in the browser. Alternatively, you could have used the print() statement in place of the echo statement. Using echo or print() is a matter of taste; when you look at other people’s scripts, you might see either used, which is why I included both here.

Referring back to the code you have seen so far, note the only line of code in Listing 4.1 ended with a semicolon. The semicolon informs the PHP engine that you have completed a statement, and is probably the most important bit of coding syntax you could learn at this stage.

A statement represents an instruction to the PHP engine. Broadly, it is to PHP what a sentence is to written or spoken English. A sentence should usually end with a period; a statement should usually end with a semicolon. Exceptions to this rule include statements that enclose other statements and statements that end a block of code. In most cases, however, failure to end a statement with a semicolon will confuse the PHP engine and result in an error.

Combining HTML and PHP

The script in Listing 4.1 is pure PHP. You can incorporate this into an HTML document by simply adding HTML outside the PHP start and end tags, as shown in Listing 4.2.

Listing 4.2 A PHP Script Incorporated into HTML

1: <!DOCTYPE html>
2: <html>
3: <head>
4: <title>A PHP script including HTML</title>
5: </head>
6: <body>
7: <h1><?php echo "hello world"; ?></h1>
8: </body>
9: </html>

As you can see, incorporating PHP code into a predominantly HTML document is simply a matter of typing in the code. The PHP engine ignores everything outside the PHP open and close tags. If you were to save the contents of Listing 4.2 as helloworld.php, place it in your document root, and then view it with a browser, as shown in Figure 4.3, you would see the string hello world in a bold heading. If you were to view the document source, as shown in Figure 4.4, the listing would look exactly like a normal HTML document.


Figure 4.3 The output of helloworld.php as viewed in a browser.


Figure 4.4 The output of helloworld.php as HTML source code.

You can include as many blocks of PHP code as you need in a single document, interspersing them with HTML as required. Although you can have multiple blocks of code in a single document, they combine to form a single script. Any variables defined in the first block will usually be available to subsequent blocks.

Adding Comments to PHP Code

Code that seems clear at the time you write it can seem like a hopeless tangle when you try to amend it 6 months later. Adding comments to your code as you write can save you time later on and make it easier for other programmers to work with your code.

A comment is text in a script that is ignored by the PHP engine. Comments can make code more readable or annotate a script.

Single-line comments begin with two forward slashes (//)—the preferred style—or a single hash or pound sign (#). The PHP engine ignores all text between these marks and either the end of the line or the PHP close tag:

// this is a comment
# this is another comment

Multiline comments begin with a forward slash followed by an asterisk (/*) and end with an asterisk followed by a forward slash (*/):

this is a comment
none of this will
be parsed by the
PHP engine


In this chapter, you learned how to install and configure PHP 5.4.0 for use with Apache on Linux/UNIX, Mac OS X, or Windows. You learned that various configure options in the Linux/UNIX build script can change the features that are supported. You learned about php.ini and how to change the values of its directives.

Using the phpinfo() function, you tested your installation and produced a list of its configuration values. You created a simple PHP script using a text editor. You examined four sets of tags that you can use to begin and end blocks of PHP code.

Finally, you learned how to use the echo and print statements to send data to the browser, and you brought HTML and PHP together into the same script. In the next chapter, you use these skills to test some of the fundamental building blocks of the PHP language, including variables, data types, and operators.


Q. This chapter covered an installation for Linux/UNIX, Mac OS X, or Windows, and the Apache web server. Does this mean that the material presented in this book will not apply to other servers and operating systems?

A. No. One of PHP’s great strengths is that it runs on multiple platforms. You can find installation instructions for different web servers and configuration directives for database support in the PHP Manual. Although the examples throughout this book are specifically geared toward the combination of PHP, MySQL, and Apache, only slight modifications are needed to work with the examples using different web servers or databases.

Q. Which are the best start and end tags to use?

A. It is largely a matter of preference. For the sake of portability, the standard tags (<?php ?>) are preferred.

Q. What editors should I avoid when creating PHP code?

A. Do not use word processors that format text for printing (Microsoft Word, for example). Even if you save files created using this type of editor in plaintext format, hidden characters are likely to creep into your code.

Q. When should I comment my code?

A. Again, this is a matter of preference. Some short scripts will be self-explanatory even after a long interval. For scripts of any length or complexity, you should comment your code. Comments in your code often save you time and frustration in the long run.


The workshop is designed to help you review what you’ve learned and begin putting your knowledge into practice.


1. From a Linux/UNIX operating system, how would you get help on configuration options (the options that you pass to the configure script in your PHP distribution)?

2. What line should you add to the Apache configuration file to ensure that the .php extension is recognized?

3. What is PHP’s configuration file called?

4. Can a person browsing your website read the source code of PHP script you have successfully installed?


1. You can get help on configuration options by calling the configure script in the PHP distribution folder and passing it the --help argument:

./configure --help

2. This line ensures that Apache will treat files ending with the .php extension as PHP scripts:

AddType application/x-httpd-php .php

3. PHP’s configuration file is called php.ini.

4. No, the user will see only the output of your script.


1. Install PHP on your system. If it is already in place, review your php.ini file and check your configuration.

2. Familiarize yourself with the process of creating, uploading, and running PHP scripts. In particular, create your own “Hello World” script. Add HTML code to it, and add additional blocks of PHP. Experiment with the different PHP delimiter tags. Which ones are enabled in your configuration? Take a look at your php.ini file to confirm your findings. Don’t forget to add some comments to your code.