Tuesday, July 14, 2009

Beginning PHP and Oracle From Novice to Professional by W. Jason Gilmore and Bob Bryla Chapter 2

Chances are you’re going to rely upon an existing corporate IT infrastructure or a third-party Web hosting provider for hosting your PHP-driven Web sites, alleviating you of the need to attain a deep
understanding of how to build and administrate a Web server. However, as most prefer to develop applications on a local workstation or laptop, or on a dedicated development server, you’re likely going to need to know how to at least install and configure PHP and a Web server (in this case, Apache and Microsoft IIS).
Having at least a rudimentary understanding of this process has a second benefit as well: it provides you with the opportunity to learn more about the many features of PHP and the Web server, which might not otherwise be commonly touted. This knowledge can be useful not only in terms of helping you to evaluate whether your Web environment is suited to your vision for a particular project, but also in terms of aiding you in troubleshooting problems with installing third-party software (which may arise due to a misconfigured or hobbled PHP installation).
To that end, in this chapter you’ll be guided through the process of installing PHP on both the Windows and Linux platforms. Because PHP is of little use without a Web server, along the way you’ll learn how to install and configure Apache on both Windows and Linux, and Microsoft IIS 7 on Windows.
This chapter concludes with an overview of select PHP editors and IDEs (integrated develop- ment environments), and shares some insight into what you should keep in mind when choosing a Web hosting provider.
Specifically, you’ll learn how to do the following:

• Install Apache and PHP on the Linux platform

• Install Apache, IIS, and PHP on the Microsoft Windows platform

• Test your installation to ensure that all of the components are properly working and trouble- shoot common pitfalls
• Configure PHP to satisfy practically every conceivable requirement

• Choose an appropriate PHP IDE to help you write code faster and more efficiently

• Choose a Web hosting provider suited to your specific needs

Installation Prerequisites

Let’s begin the installation process by downloading the necessary software. At a minimum, this will entail downloading PHP and the appropriate Web server (either Apache or IIS 7, depending on your platform and preference). If your platform requires additional downloads, that information will be provided in the appropriate section.

9

■Tip In this chapter you’ll be guided through the manual installation and configuration process. Manually installing and configuring Apache and PHP is a good idea because it will familiarize you with the many configuration options at your disposal, allowing you to ultimately wield greater control over how your Web sites operate. However, if you’re ultimately going to rely on the services of a Web hosting provider and just want to quickly set up a test environment so you can get to coding, consider downloading XAMPP (http://www.apachefriends.org/en/xampp.html), a free automated Apache installer that includes, among other things, PHP, Perl, and MySQL. XAMPP is available for Linux and Windows, with Mac OS X and Solaris solutions in development.

Downloading Apache

These days, Apache is packaged with all mainstream Linux distributions, meaning if you’re using one of these platforms, chances are quite good you already have it installed or can easily install it through your distribution’s packaging service (e.g., by running the apt-get command on Ubuntu). Therefore, if this applies to you, by all means skip this section and proceed to the section “Down- loading PHP.” However, if you’d like to install Apache manually, follow along with this section.
Because of tremendous daily download traffic, it’s suggested you choose a download location most closely situated to your geographical location (known as a mirror). At the time of this writing, the following page offered a listing of 251 mirrors located in 52 global regions: http://www.apache.org/ mirrors/.
Navigate to this page and choose a suitable mirror by clicking the appropriate link. The resulting
page will consist of a list of directories representing all projects found under the Apache Software Foundation umbrella. Enter the httpd directory. This will take you to the page that includes links to the most recent Apache releases and various related projects and utilities. The distribution is avail- able in two formats:

Source: If your target server platform is Linux, consider downloading the source code. Although there is certainly nothing wrong with using one of the convenient binary versions, the extra time invested in learning how to compile from source will provide you with greater configura- tion flexibility. If your target platform is Windows and you’d like to compile from source, a separate source package intended for the Win32 platform is available for download. However, note that this chapter does not discuss the Win32 source installation process. Instead, this chapter focuses on the much more commonplace (and recommended) binary installer.

Binary: Binaries are available for a number of operating systems, among them Microsoft
Windows, Sun Solaris, and OS/2. You’ll find these binaries under the binaries directory.

So which Apache version should you download? Although Apache 2 was released more than five years ago, version 1.X remains in widespread use. In fact, it seems that the majority of shared-server ISPs have yet to migrate to version 2.X. The reluctance to upgrade doesn’t have anything to do with issues regarding version 2.X, but rather is a testament to the amazing stability and power of version 1.X. For standard use, the external differences between the two versions are practically undetectable; therefore, consider going with Apache 2 to take advantage of its enhanced stability. In fact, if you plan to run Apache on Windows for either development or deployment purposes, it is recommended that you choose version 2 because it is a complete rewrite of the previous Windows distribution and is significantly more stable than its predecessor.

Downloading PHP

Although PHP comes bundled with most Linux distributions nowadays, you should download the latest stable version from the PHP Web site. To decrease download time, choose from the approxi- mately 100 mirrors residing in more than 50 countries, a list of which is available here: http:// www.php.net/mirrors.php.
Once you’ve chosen the closest mirror, navigate to the downloads page and choose one of the available distributions:

Source: If Linux is your target server platform, or if you plan to compile from source for the Windows platform, choose this distribution format. Building from source on Windows isn’t recommended and isn’t discussed in this book. Unless your situation warrants very special circumstances, the prebuilt Windows binary will suit your needs just fine. This distribution is compressed in Bzip2 and Gzip formats. Keep in mind that the contents are identical; the different compression formats are just there for your convenience.

Windows zip package: If you plan to use PHP in conjunction with Apache on Windows, you should download this distribution because it’s the focus of the later installation instructions.

Windows installer: This version offers a convenient Windows installer interface for installing and configuring PHP, and support for automatically configuring the IIS, PWS, and Xitami servers. Although you could use this version in conjunction with Apache, it is not recommended. Instead, use the Windows zip package version. Further, if you’re interested in configuring PHP to run with IIS, see the later section titled “Installing IIS and PHP on Windows.” A recent collaboration between Microsoft and PHP product and services leader Zend Technologies Ltd. has resulted in a greatly improved process that is covered in that section.

If you are interested in playing with the very latest PHP development snapshots, you can down- load both source and binary versions at http://snaps.php.net/. Keep in mind that some of the versions made available via this Web site are not intended for use with live Web sites.

Obtaining the Documentation

Both the Apache and PHP projects offer truly exemplary documentation, covering practically every aspect of the respective technology in lucid detail. You can view the latest respective versions online via http://httpd.apache.org/ and http://www.php.net/, or download a local version to your local machine and read it there.

Downloading the Apache Manual

Each Apache distribution comes packaged with the latest versions of the documentation in XML and HTML formats and in nine languages (Brazilian Portuguese, Chinese, Dutch, English, German, Japa- nese, Russian, Spanish, and Turkish). The documentation is located in the directory docs, found in the installation root directory.
Should you need to upgrade your local version, require an alternative format such as PDF or
Microsoft Compiled HTML Help (CHM) files, or want to browse it online, proceed to the following
Web site: http://httpd.apache.org/docs-project/.

Downloading the PHP Manual

The PHP documentation is available in more than 20 languages and in a variety of formats, including a single HTML page, multiple HTML pages, and CHM files. These versions are generated from DocBook- based master files, which can be retrieved from the PHP project’s CVS server should you wish to convert to another format. The documentation is located in the directory manual in the installation directory.
Should you need to upgrade your local version or retrieve an alternative format, navigate to the following page and click the appropriate link: http://www.php.net/docs.php.

Installing Apache and PHP on Linux

This section guides you through the process of building Apache and PHP from source, targeting the Linux platform. You need a respectable ANSI-C compiler and build system, two items that are commonplace on the vast majority of distributions available today. In addition, PHP requires both Flex (http://flex.sourceforge.net/) and Bison (http://www.gnu.org/software/bison/bison.html), while Apache requires at least Perl version 5.003. If you’ve downloaded PHP 6, you’ll also need to install the International Components for Unicode (ICU) package version 3.4 (http://icu.sourceforge.net/), although this may very well be bundled with PHP in the future. Again, all of these items are prevalent on most, if not all, modern Linux platforms. Finally, you’ll need root access to the target server to complete the build process.
For the sake of convenience, before beginning the installation process, consider moving both packages to a common location—/usr/src/, for example. The installation process follows:

1. Unzip and untar Apache and PHP. In the following code, the X represents the latest stable version numbers of the distributions you downloaded in the previous section:

%>gunzip httpd-2_X_XX.tar.gz
%>tar xvf httpd-2_X_XX.tar
%>gunzip php-XX.tar.gz
%>tar xvf php-XX.tar

2. Configure and build Apache. At a minimum, you’ll want to pass the option --enable-so, which tells Apache to enable the ability to load shared modules:
%>cd httpd-2_X_XX
%>./configure --enable-so [other options]
%>make

3. Install Apache:

%>make install

4. Configure, build, and install PHP (see the section “Configuring PHP at Build Time on Linux” for information regarding modifying installation defaults and incorporating third-party extensions into PHP). In the following steps, APACHE_INSTALL_DIR is a placeholder for the path to Apache’s installed location, for instance /usr/local/apache2:

%>cd ../php-X_XX
%>./configure --with-apxs2=APACHE_INSTALL_DIR/bin/apxs [other options]
%>make
%>make install

5. PHP comes bundled with a configuration file that controls many aspects of PHP’s behavior.
This file is known as php.ini, but it was originally named php.ini-dist. You need to copy this file to its appropriate location and rename it php.ini. The later section “Configuring PHP” examines php.ini’s purpose and contents in detail. Note that you can place this configu- ration file anywhere you please, but if you choose a nondefault location, you also need to configure PHP using the --with-config-file-path option. Also note that there is another default configuration file at your disposal, php.ini-recommended. This file sets various non- standard settings and is intended to better secure and optimize your installation, although this configuration may not be fully compatible with some of the legacy applications. Con- sider using this file in lieu of php.ini-dist. To use this file, execute the following command:

%>cp php.ini-recommended /usr/local/lib/php.ini

6. Open Apache’s configuration file, known as httpd.conf, and verify that the following lines exist. ( The httpd.conf file is located at APACHE_INSTALL_DIR/conf/httpd.conf.) If they don’t exist, go ahead and add them. Consider adding each alongside the other LoadModule and AddType entries, respectively:

LoadModule php6_module modules/libphp6.so
AddType application/x-httpd-php .php

Because at the time of publication PHP 6 wasn’t yet official, you should use the latest stable version of PHP 5 if you’re planning on running any production applications. In the case of PHP 5, the lines will look like this:

LoadModule php5_module modules/libphp5.so
AddType application/x-httpd-php .php

Believe it or not, that’s it. Restart the Apache server with the following command:

%>/usr/local/apache2/bin/apachectl restart

Now proceed to the section “Testing Your Installation.”

■Tip The AddType directive in step 6 binds a MIME type to a particular extension or extensions. The .php exten-
sion is only a suggestion; you can use any extension you like, including .html, .php5, or even .jason. In addition, you can designate multiple extensions simply by including them all on the line, each separated by a space. While some users prefer to use PHP in conjunction with the .html extension, keep in mind that doing so will ultimately cause the file to be passed to PHP for parsing every single time an HTML file is requested. Some people may consider this convenient, but it will come at the cost of performance.

Installing Apache and PHP on Windows

Whereas previous Windows-based versions of Apache weren’t optimized for the Windows platform, Apache 2 was completely rewritten to take advantage of Windows platform-specific features. Even if you don’t plan to deploy your application on Windows, it nonetheless makes for a great localized testing environment for those users who prefer it over other platforms. The installation process follows:

1. Start the Apache installer by double-clicking the apache_X.X.XX-win32-x86-no_ssl.msi icon.
The Xs in this file name represent the latest stable version numbers of the distributions you downloaded in the previous section.

2. The installation process begins with a welcome screen. Take a moment to read the screen and then click Next.
3. The license agreement is displayed next. Carefully read through the license. Assuming that you agree with the license stipulations, click Next.
4. A screen containing various items pertinent to the Apache server is displayed next. Take a moment to read through this information and then click Next.
5. You will be prompted for various items pertinent to the server’s operation, including the network domain, the server name, and the administrator’s e-mail address. If you know this information, fill it in now; otherwise, just enter localhost for the first two items and put in any e-mail address for the last. You can always change this information later in the httpd.conf file. You’ll also be prompted as to whether Apache should run as a service for all users or only for the current user. If you want Apache to automatically start with the operating system, which is recommended, then choose to install Apache as a service for all users. When you’re finished, click Next.
6. You are prompted for a Setup Type: Typical or Custom. Unless there is a specific reason you don’t want the Apache documentation installed, choose Typical and click Next. Otherwise, choose Custom, click Next, and on the next screen, uncheck the Apache Documentation option.
7. You’re prompted for the Destination folder. By default, this is C:\Program Files\Apache Group. Consider changing this to C:\, which will create an installation directory C:\apache2\. Regardless of what you choose, keep in mind that the latter is used here for the sake of con- vention. Click Next.
8. Click Install to complete the installation. That’s it for Apache. Next you’ll install PHP.

9. Unzip the PHP package, placing the contents into C:\php6\. You’re free to choose any installation directory you please, but avoid choosing a path that contains spaces. Regardless, the instal- lation directory C:\php6\ will be used throughout this chapter for consistency.
10. Navigate to C:\apache2\conf and open httpd.conf for editing.

11. Add the following three lines to the httpd.conf file. Consider adding them directly below the block of LoadModule entries located in the bottom of the Global Environment section:
LoadModule php6_module c:/php6/php6apache2.dll
AddType application/x-httpd-php .php
PHPIniDir "c:\php6"

Because at the time of publication PHP 6 wasn’t yet official, you should use the latest stable version of PHP 5 if you’re planning on running any production applications. To do so, you’ll need to make some minor changes to the previous lines, as follows:

LoadModule php5_module c:/php5/php5apache2.dll
AddType application/x-httpd-php .php
PHPIniDir "c:\php5"

■Tip The AddType directive in step 11 binds a MIME type to a particular extension or extensions. The .php
extension is only a suggestion; you can use any extension you like, including .html, .php5, or even .jason. In addition, you can designate multiple extensions simply by including them all on the line, each separated by a space. While some users prefer to use PHP in conjunction with the .html extension, keep in mind that doing so will cause the file to be passed to PHP for parsing every single time an HTML file is requested. Some people may consider this convenient, but it will come at the cost of a performance decrease. Ultimately, it is strongly recommended you stick to common convention and use .php.

12. Rename the php.ini-dist file to php.ini and save it to the C:\php6 directory. The php.ini file contains hundreds of directives that are responsible for tweaking PHP’s behavior. The later section “Configuring PHP” examines php.ini’s purpose and contents in detail. Note that you can place this configuration file anywhere you please, but if you choose a nondefault location, you also need to configure PHP using the --with-config-file-path option. Also note that there is another default configuration file at your disposal, php.ini-recommended. This file sets various nonstandard settings and is intended to better secure and optimize your instal- lation, although this configuration may not be fully compatible with some of the legacy applications. Consider using this file in lieu of php.ini-dist.
13. If you’re using Windows NT, 2000, XP, or Vista, navigate to Start ➤ Settings ➤ Control Panel ➤ Administrative Tools ➤ Services. If you’re running Windows 98, see the instructions provided at the conclusion of the next step.
14. Locate Apache in the list and make sure that it is started. If it is not started, highlight the label and click Start the Service, located to the left of the label. If it is started, highlight the label and click Restart the Service, so that the changes made to the httpd.conf file take effect. Next, right-click Apache and choose Properties. Ensure that the startup type is set to Automatic. If you’re still using Windows 95/98, you need to start Apache manually via the shortcut provided on the start menu.

Installing IIS and PHP on Windows

Microsoft Windows remains the operating system of choice even among most open source–minded developers, largely due to reasons of convenience; after all, as the dominant desktop operating system, it makes sense that most would prefer to continue using this familiar environment. Yet for reasons of both stability and performance, deploying PHP-driven Web sites on Linux running an Apache Web server has historically been the best choice.
But this presents a problem if you’d like to develop and even deploy your PHP-driven Web site on a Windows server running the Microsoft IIS Web server. Microsoft, in collaboration with PHP products and services provider Zend Technologies Ltd., is seeking to eliminate this inconvenience through a new IIS component called FastCGI. FastCGI greatly improves the way IIS interacts with certain third-party applications that weren’t written with IIS in mind, including PHP (versions 5.X and newer are supported). Though FastCGI wasn’t intended for use within production environments at the time of publication, it is ready for testing and development purposes. In this section you’ll learn how to configure PHP to run in conjunction with IIS.

Installing IIS and PHP

To begin, download PHP as explained in the earlier section “Downloading PHP.” Be sure to choose the Windows zip package distribution as described in that section. Extract the zip file to C:\php. Believe it or not, this is all that’s required in regard to installing PHP.
Next you’ll need to install IIS. In order to take advantage of FastCGI, you’ll need to install IIS version 5.1 or greater. IIS 5.1 is available for Windows 2000 Professional, Windows 2000 Server, and Windows XP Professional, whereas IIS 6 is available for Windows 2003 Server. You can verify whether
IIS is installed on these operating systems by navigating to Start ➤ Run and executing inetmgr at the
prompt. If the IIS manager loads, it’s installed and you can proceed to the next section, “Configuring FastCGI to Manage PHP Processes.” If it is not installed, insert the Windows XP Professional CD into your CD-ROM drive and navigate to Start ➤ Control Panel ➤ Add/Remove Programs, and select Add/ Remove Windows Components. From here, check the box next to Internet Information Services (IIS) and click Next, then click OK.

■Note It’s not possible to download any version of IIS; they are bundled solely with the corresponding version of Windows, therefore you will need the Windows installation disk if IIS isn’t already installed on your computer. Also, IIS is not available nor installable on Windows 98, Windows ME, or Windows XP Home Edition.

IIS 7 is bundled with both Windows Vista and Windows Server “Longhorn”; however, it may not be installed on your machine. You can verify whether IIS is installed on these operating systems by
navigating to Start ➤ Run and executing inetmgr at the prompt. If the IIS manager loads, it’s installed,
and you can proceed to the next section, “Configuring FastCGI to Manage PHP Processes.” Other- wise, install IIS 7 by navigating to Start ➤ Settings ➤ Control Panel ➤ Programs and Features and clicking the Turn Windows Features On and Off link appearing to the right of the window. As shown in Figure 2-1, a new window will appear containing a list of features you’re free to enable and disable at will, including IIS. Enable IIS by clicking the checkbox next to it.
You’ll also want to enable FastCGI by clicking the checkbox next to CGI. Once both of these checkboxes have been enabled, click the OK button.
Once the installation process completes, you’ll need to restart the operating system for the changes to take effect.

Figure 2-1. Enabling IIS on Vista

Configuring FastCGI to Manage PHP Processes

Next you’ll need to configure FastCGI to handle PHP-specific requests. This is done by navigating to the IIS Manager (Start ➤ Run, then enter inetmgr), clicking Handler Mappings, clicking Add Module Mapping, and then entering the mapping as shown in Figure 2-2.
PHP and IIS are now properly installed and configured on your machine. Proceed to the next section to test your installation.

Figure 2-2. Confirming the FastCGI Handler Mapping is installed

Testing Your Installation

The best way to verify your PHP installation is by attempting to execute a PHP script. Open a text editor and add the following lines to a new file:
<?php phpinfo();
?>

If you’re running Apache, save the file within the htdocs directory as phpinfo.php. If you’re
running IIS, save the file within C:\inetpub\wwwroot\.
Now open a browser and access this file by entering the following URL: http://localhost/
phpinfo.php.
If all goes well, you should see output similar to that shown in Figure 2-3. If you’re attempting to run this script on a Web hosting provider’s server, and you receive an error message stating phpinfo() has been disabled for security reasons, you’ll need to try executing another script. Try executing this one instead, which should produce some simple output:

<?php
echo "A simple but effective PHP test!";
?>

■Tip Executing the phpinfo() function is a great way to learn about your PHP installation, as it offers extensive information regarding the server, operating system environment, and available extensions.

Figure 2-3. Output from PHP’s phpinfo() function

If you encountered no noticeable errors during the build process but you are not seeing the appropriate output, it may be due to one or more of the following reasons:

• Changes made to Apache’s configuration file do not take effect until it has been restarted.
Therefore, be sure to restart Apache after adding the necessary PHP-specific lines to the
httpd.conf file.

• When you modify the Apache configuration file, you may accidentally introduce an invalid character, causing Apache to fail upon an attempt to restart. If Apache will not start, go back and review your changes.
• Verify that the file ends in the PHP-specific extension as specified in the httpd.conf file. For example, if you’ve defined only .php as the recognizable extension, don’t try to embed PHP code in an .html file.
• Make sure that you’ve delimited the PHP code within the file. Neglecting to do this will cause the code to output to the browser.

• You’ve created a file named index.php and are trying unsuccessfully to call it as you would a default directory index. Remember that by default, Apache only recognizes index.html in this fashion. Therefore, you need to add index.php to Apache’s DirectoryIndex directive.
• If you’re running IIS, make sure the appropriate mapping is available, as shown in Figure 2-2.
If not, something went awry during the FastCGI installation process. Try removing that mapping and installing FastCGI anew.

Configuring PHP

Although the base PHP installation is sufficient for most beginning users, chances are you’ll soon want to make adjustments to the default configuration settings and possibly experiment with some of the third-party extensions that are not built into the distribution by default. In this section you’ll learn all about how to tweak PHP’s behavior and features to your specific needs.

Configuring PHP at Build Time on Linux

Building PHP as described earlier in the chapter is sufficient for getting started; however, you should keep in mind many other build-time options are at your disposal. You can view a complete list of configuration flags (there are more than 200) by executing the following:

%>./configure --help

To make adjustments to the build process, you just need to add one or more of these arguments to PHP’s configure command, including a value assignment if necessary. For example, suppose you want to enable PHP’s FTP functionality, a feature not enabled by default. Just modify the configura- tion step of the PHP build process like so:

%>./configure --with-apxs2=/usr/local/apache2/bin/apxs --enable-ftp

As another example, suppose you want to enable PHP’s Java extension. Just reconfigure PHP
like so:

%>./configure --with-apxs2=/usr/local/apache2/bin/apxs \
>--enable-java=[JDK-INSTALL-DIR]

One common point of confusion among beginners is to assume that simply including addi- tional flags will automatically make this functionality available via PHP. This is not necessarily the case. Keep in mind that you also need to install the software that is ultimately responsible for enabling the extension support. In the case of the Java example, you need the Java Development Kit (JDK).

Customizing the Windows Build

A total of 45 extensions are bundled with PHP 5.1 and 5.2, a number that was pared to 35 extensions with the current alpha version of PHP 6. However, to actually use any of these extensions, you need to uncomment the appropriate line within the php.ini file. For example, if you’d like to enable PHP’s XML-RPC extension, you need to make a few minor adjustments to your php.ini file:

1. Open the php.ini file and locate the extension_dir directive and assign it C:\php\ext\. If you installed PHP in another directory, modify this path accordingly.
2. Locate the line ;extension=php_xmlrpc.dll. Uncomment this line by removing the preceding semicolon. Save and close the file.

3. Restart the Web server and the extension is ready for use from within PHP. Keep in mind that some extensions have additional configuration directives that may be found later in the php.ini file.

When enabling these extensions, you may occasionally need to install other software. See the
PHP documentation for more information about each respective extension.

Run-Time Configuration

It’s possible to change PHP’s behavior at run time on both Windows and Linux through the php.ini file. This file contains a myriad of configuration directives that collectively control the behavior of each product. The remainder of this chapter focuses on PHP’s most commonly used configuration directives, introducing the purpose, scope, and default value of each.

Managing PHP’s Configuration Directives

Before you delve into the specifics of each directive, this section demonstrates the various ways in which these directives can be manipulated, including through the php.ini file, Apache’s httpd.conf and .htaccess files, and directly through a PHP script.

The php.ini File

The PHP distribution comes with two configuration templates, php.ini-dist and php.ini-recommended. You’ll want to rename one of these files to php.ini and place it in the location specified by the PHPIniDir directive found in Apache’s httpd.conf file. It’s suggested that you use the latter because many of the parameters found within it are already assigned their suggested settings. Taking this advice will likely save you a good deal of initial time and effort securing and tweaking your installation because there are well over 200 distinct configuration parameters in this file. Although the default values go a long way toward helping you to quickly deploy PHP, you’ll probably want to make additional adjustments to PHP’s behavior, so you’ll need to learn a bit more about php.ini and its many configuration parameters. The upcoming section “PHP’s Configuration Directives” presents a comprehensive introduction to many of these parameters, explaining the purpose, scope, and range of each.
The php.ini file is PHP’s global configuration file, much like httpd.conf is to Apache. This file
addresses 12 different aspects of PHP’s behavior:

• Language Options

• Safe Mode

• Syntax Highlighting

• Miscellaneous

• Resource Limits

• Error Handling and Logging

• Data Handling

• Paths and Directories

• File Uploads

• Fopen Wrappers

• Dynamic Extensions

• Module Settings

The section “PHP’s Configuration Directives” that follows will introduce many of the directives found in the php.ini file. Later chapters will introduce module-specific directives as appropriate.
Before you are introduced to them, however, take a moment to review the php.ini file’s general syntactical characteristics. The php.ini file is a simple text file, consisting solely of comments and the directives and their corresponding values. Here’s a sample snippet from the file:

;
; Allow the <? tag
;
short_open_tag = Off
Lines beginning with a semicolon are comments; the parameter short_open_tag is assigned the value Off.

■Tip Once you’re comfortable with a configuration parameter’s purpose, consider deleting the accompanying
comments to streamline the file’s contents, thereby decreasing later editing time.

Exactly when changes take effect depends on how you install PHP. If PHP is installed as a CGI binary, the php.ini file is reread every time PHP is invoked, thus making changes instantaneous. If PHP is installed as an Apache module, php.ini is only read in once, when the Apache daemon is first started. Therefore, if PHP is installed in the latter fashion, you must restart Apache before any of the changes take effect.

The Apache httpd.conf and .htaccess Files

When PHP is running as an Apache module, you can modify many of the directives through either the httpd.conf file or the .htaccess file. This is accomplished by prefixing directive/value assign- ment with one of the following keywords:

• php_value: Sets the value of the specified directive.

• php_flag: Sets the value of the specified Boolean directive.

• php_admin_value: Sets the value of the specified directive. This differs from php_value in that it cannot be used within an .htaccess file and cannot be overridden within virtual hosts or
.htaccess.

• php_admin_flag: Sets the value of the specified directive. This differs from php_value in that it cannot be used within an .htaccess file and cannot be overridden within virtual hosts or
.htaccess.

For example, to disable the short tags directive and prevent others from overriding it, add the following line to your httpd.conf file:

php_admin_flag short_open_tag Off

Within the Executing Script

The third, and most localized, means for manipulating PHP’s configuration variables is via the ini_set() function. For example, suppose you want to modify PHP’s maximum execution time for a given script. Just embed the following command into the top of the script:

ini_set("max_execution_time","60");

Configuration Directive Scope

Can configuration directives be modified anywhere? The answer is no, for a variety of reasons, mostly security related. Each directive is assigned a scope, and the directive can be modified only within that scope. In total, there are four scopes:

• PHP_INI_PERDIR: Directive can be modified within the php.ini, httpd.conf, or .htaccess files

• PHP_INI_SYSTEM: Directive can be modified within the php.ini and httpd.conf files

• PHP_INI_USER: Directive can be modified within user scripts

• PHP_INI_ALL: Directive can be modified anywhere

PHP’s Configuration Directives

The following sections introduce many of PHP’s core configuration directives. In addition to a general definition, each section includes the configuration directive’s scope and default value. Because you’ll probably spend the majority of your time working with these variables from within the php.ini file, the directives are introduced as they appear in this file.
Note that the directives introduced in this section are largely relevant solely to PHP’s general
behavior; directives pertinent to extensions, or to topics in which considerable attention is given later in the book, are not introduced in this section but rather are introduced in the appropriate chapter.

Language Options

The directives located in this section determine some of the language’s most basic behavior. You’ll definitely want to take a few moments to become acquainted with these configuration possibilities.

engine = On | Off

Scope: PHP_INI_ALL; Default value: On
This parameter is responsible for determining whether the PHP engine is available. Turning it off prevents you from using PHP at all. Obviously, you should leave this enabled if you plan to use PHP.

zend.ze1_compatibility_mode = On | Off

Scope: PHP_INI_ALL; Default value: Off
Some three years after PHP 5.0 was released, PHP 4.X is still in widespread use. One of the reasons for the protracted upgrade cycle is due to some significant object-oriented incompatibilities between PHP 4 and 5. The zend.ze1_compatibility_mode directive attempts to revert several of these changes in PHP 5, raising the possibility that PHP 4 applications can continue to run without change in version 5.

■Note The zend.ze1_compatibility_mode directive never worked as intended and was removed in PHP 6.

short_open_tag = On | Off

Scope: PHP_INI_ALL; Default value: On
PHP script components are enclosed within escape syntax. There are four different escape formats, the shortest of which is known as short open tags, which looks like this:

<?
echo "Some PHP statement";
?>

You may recognize that this syntax is shared with XML, which could cause issues in certain environ-
ments. Thus, a means for disabling this particular format has been provided. When short_open_tag is enabled (On), short tags are allowed; when disabled (Off), they are not.

asp_tags = On | Off

Scope: PHP_INI_ALL; Default value: Off
PHP supports ASP-style script delimiters, which look like this:

<%
echo "Some PHP statement";
%>

If you’re coming from an ASP background and prefer to continue using this delimiter syntax,
you can do so by enabling this tag.

■Note ASP-style tags are no longer available as of PHP 6.

precision = integer

Scope: PHP_INI_ALL; Default value: 12
PHP supports a wide variety of datatypes, including floating-point numbers. The precision parameter specifies the number of significant digits displayed in a floating-point number representation. Note that this value is set to 14 digits on Win32 systems and to 12 digits on Linux.

y2k_compliance = On | Off

Scope: PHP_INI_ALL; Default value: Off
Who can forget the Y2K scare of just a few years ago? Superhuman efforts were undertaken to eliminate the problems posed by non-Y2K-compliant software, and although it’s very unlikely, some users may be using wildly outdated, noncompliant browsers. If for some bizarre reason you’re sure that a number of your site’s users fall into this group, then disable the y2k_compliance parameter; otherwise, it should be enabled.

output_buffering = On | Off | integer

Scope: PHP_INI_SYSTEM; Default value: Off
Anybody with even minimal PHP experience is likely quite familiar with the following two messages:

"Cannot add header information – headers already sent" "Oops, php_set_cookie called after header has been sent"

These messages occur when a script attempts to modify a header after it has already been sent back to the requesting user. Most commonly they are the result of the programmer attempting to send a cookie to the user after some output has already been sent back to the browser, which is impossible to accomplish because the header (not seen by the user, but used by the browser) will always precede that output. PHP version 4.0 offered a solution to this annoying problem by introducing the concept

of output buffering. When enabled, output buffering tells PHP to send all output at once, after the script has been completed. This way, any subsequent changes to the header can be made throughout the script because it hasn’t yet been sent. Enabling the output_buffering directive turns output buff- ering on. Alternatively, you can limit the size of the output buffer (thereby implicitly enabling output buffering) by setting it to the maximum number of bytes you’d like this buffer to contain.
If you do not plan to use output buffering, you should disable this directive because it will hinder performance slightly. Of course, the easiest solution to the header issue is simply to pass the infor- mation before any other content whenever possible.

output_handler = string

Scope: PHP_INI_ALL; Default value: NULL
This interesting directive tells PHP to pass all output through a function before returning it to the requesting user. For example, suppose you want to compress all output before returning it to the browser, a feature supported by all mainstream HTTP/1.1-compliant browsers. You can assign output_handler like so:

output_handler = "ob_gzhandler"

ob_gzhandler() is PHP’s compression-handler function, located in PHP’s output control library. Keep in mind that you cannot simultaneously set output_handler to ob_gzhandler() and enable zlib.output_compression (discussed next).

zlib.output_compression = On | Off | integer

Scope: PHP_INI_SYSTEM; Default value: Off
Compressing output before it is returned to the browser can save bandwidth and time. This HTTP/1.1 feature is supported by most modern browsers and can be safely used in most applications. You enable automatic output compression by setting zlib.output_compression to On. In addition, you can simultaneously enable output compression and set a compression buffer size (in bytes) by assigning zlib.output_compression an integer value.

zlib.output_handler = string

Scope: PHP_INI_SYSTEM; Default value: NULL
The zlib.output_handler specifies a particular compression library if the zlib library is not available.

implicit_flush = On | Off

Scope: PHP_INI_SYSTEM; Default value: Off
Enabling implicit_flush results in automatically clearing, or flushing, the output buffer of its contents after each call to print() or echo(), and completing each embedded HTML block. This might be useful in an instance where the server requires an unusually long period of time to compile results or perform certain calculations. In such cases, you can use this feature to output status updates to the user rather than just wait until the server completes the procedure.

unserialize_callback_func = string

Scope: PHP_INI_ALL; Default value: NULL
This directive allows you to control the response of the unserializer when a request is made to instantiate an undefined class. For most users, this directive is irrelevant because PHP already outputs a warning in such instances if PHP’s error reporting is tuned to the appropriate level.

serialize_precision = integer

Scope: PHP_INI_ALL; Default value: 100
The serialize_precision directive determines the number of digits stored after the floating point when doubles and floats are serialized. Setting this to an appropriate value ensures that the precision is not potentially lost when the numbers are later unserialized.

allow_call_time_pass_reference = On | Off

Scope: PHP_INI_SYSTEM; Default value: On
Function arguments can be passed in two ways: by value and by reference. Exactly how each argument is passed to a function at function call time can be specified in the function definition, which is the recommended means for doing so. However, you can force all arguments to be passed by reference at function call time by enabling allow_call_time_pass_reference.
The discussion of PHP functions in Chapter 4 addresses how functional arguments can be passed both by value and by reference, and the implications of doing so.

Safe Mode

When you deploy PHP in a multiuser environment, such as that found on an ISP’s shared server, you might want to limit its functionality. As you might imagine, offering all users full reign over all PHP’s functions could open up the possibility for exploiting or damaging server resources and files. As a safeguard for using PHP on shared servers, PHP can be run in a restricted, or safe, mode.
Enabling safe mode will disable quite a few functions and various features deemed to be potentially insecure and thus possibly damaging if they are misused within a local script. A small sampling of these disabled functions and features includes parse_ini_file(), chmod(), chown(), chgrp(), exec(), system(), and backtick operators. Enabling safe mode also ensures that the owner of the executing script matches the owner of any file or directory targeted by that script. However, this latter restric- tion in particular can have unexpected and inconvenient effects because files can often be uploaded and otherwise generated by other user IDs.
In addition, enabling safe mode opens up the possibility for activating a number of other restric-
tions via other PHP configuration directives, each of which is introduced in this section.

■Note Due in part to confusion caused by the name and approach of this particular feature, coupled with the
unintended consequences brought about due to multiple user IDs playing a part in creating and owning various files, PHP’s safe mode feature has been removed from PHP 6.

safe_mode = On | Off

Scope: PHP_INI_SYSTEM; Default value: Off
Enabling the safe_mode directive results in PHP being run under the aforementioned constraints.

safe_mode_gid = On | Off

Scope: PHP_INI_SYSTEM; Default value: Off
When safe mode is enabled, an enabled safe_mode_gid enforces a GID (group ID) check when opening files. When safe_mode_gid is disabled, a more restrictive UID (user ID) check is enforced.

safe_mode_include_dir = string

Scope: PHP_INI_SYSTEM; Default value: NULL

The safe_mode_include_dir provides a safe haven from the UID/GID checks enforced when safe_mode and potentially safe_mode_gid are enabled. UID/GID checks are ignored when files are opened from the assigned directory.

safe_mode_exec_dir = string

Scope: PHP_INI_SYSTEM; Default value: NULL
When safe mode is enabled, the safe_mode_exec_dir parameter restricts execution of executa- bles via the exec() function to the assigned directory. For example, if you want to restrict execution to functions found in /usr/local/bin, you use this directive:

safe_mode_exec_dir = "/usr/local/bin"

safe_mode_allowed_env_vars = string

Scope: PHP_INI_SYSTEM; Default value: PHP_
When safe mode is enabled, you can restrict which operating system–level environment variables users can modify through PHP scripts with the safe_mode_allowed_env_vars directive. For example, setting this directive as follows limits modification to only those variables with a PHP_ prefix:

safe_mode_allowed_env_vars = "PHP_"

Keep in mind that leaving this directive blank means that the user can modify any environment variable.

safe_mode_protected_env_vars = string

Scope: PHP_INI_SYSTEM; Default value: LD_LIBRARY_PATH
The safe_mode_protected_env_vars directive offers a means for explicitly preventing certain environment variables from being modified. For example, if you want to prevent the user from modi- fying the PATH and LD_LIBRARY_PATH variables, you use this directive:

safe_mode_protected_env_vars = "PATH, LD_LIBRARY_PATH"

open_basedir = string

Scope: PHP_INI_SYSTEM; Default value: NULL
Much like Apache’s DocumentRoot directive, PHP’s open_basedir directive can establish a base directory to which all file operations will be restricted. This prevents users from entering otherwise restricted areas of the server. For example, suppose all Web material is located within the directory
/home/www. To prevent users from viewing and potentially manipulating files like /etc/passwd via a few simple PHP commands, consider setting open_basedir like this:

open_basedir = "/home/www/"

Note that the influence exercised by this directive is not dependent upon the safe_mode directive.

disable_functions = string

Scope: PHP_INI_SYSTEM; Default value: NULL
In certain environments, you may want to completely disallow the use of certain default functions, such as exec() and system(). Such functions can be disabled by assigning them to the disable_functions parameter, like this:

disable_functions = "exec, system";

Note that the influence exercised by this directive is not dependent upon the safe_mode directive.

disable_classes = string

Scope: PHP_INI_SYSTEM; Default value: NULL
Given the capabilities offered by PHP’s embrace of the object-oriented paradigm, it likely won’t be too long before you’re using large sets of class libraries. There may be certain classes found within these libraries that you’d rather not make available, however. You can prevent the use of these classes via the disable_classes directive. For example, if you want to disable two particular classes, named vector and graph, you use the following:

disable_classes = "vector, graph"

Note that the influence exercised by this directive is not dependent upon the safe_mode directive.

ignore_user_abort = Off | On

Scope: PHP_INI_ALL; Default value: On
How many times have you browsed to a particular page only to exit or close the browser before the page completely loads? Often such behavior is harmless. However, what if the server is in the midst of updating important user profile information, or completing a commercial transaction? Enabling ignore_user_abort causes the server to ignore session termination caused by a user- or browser-initiated interruption.

Syntax Highlighting

PHP can display and highlight source code. You can enable this feature either by assigning the PHP script the extension .phps (this is the default extension and, as you’ll soon learn, can be modified) or via the show_source() or highlight_file() function. To use the .phps extension, you need to add the following line to httpd.conf:

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

You can control the color of strings, comments, keywords, the background, default text, and HTML components of the highlighted source through the following six directives. Each can be assigned an RGB, hexadecimal, or keyword representation of each color. For example, the color we commonly refer to as black can be represented as rgb(0,0,0), #000000, or black, respectively.

highlight.string = string

Scope: PHP_INI_ALL; Default value: #DD0000

highlight.comment = string

Scope: PHP_INI_ALL; Default value: #FF9900

highlight.keyword = string

Scope: PHP_INI_ALL; Default value: #007700

highlight.bg = string

Scope: PHP_INI_ALL; Default value: #FFFFFF

highlight.default = string

Scope: PHP_INI_ALL; Default value: #0000BB

highlight.html = string

Scope: PHP_INI_ALL; Default value: #000000

Miscellaneous

The Miscellaneous category consists of a single directive, expose_php.

expose_php = On | Off

Scope: PHP_INI_SYSTEM; Default value: On
Each scrap of information that a potential attacker can gather about a Web server increases the chances that he will successfully compromise it. One simple way to obtain key information about server characteristics is via the server signature. For example, Apache will broadcast the following information within each response header by default:

Apache/2.2.0 (Unix) PHP/6.0.0 PHP/6.0.0-dev Server at www.example.com Port 80

Disabling expose_php prevents the Web server signature (if enabled) from broadcasting the fact that PHP is installed. Although you need to take other steps to ensure sufficient server protection, obscuring server properties such as this one is nonetheless heartily recommended.

■Note You can disable Apache’s broadcast of its server signature by setting ServerSignature to Off in the
httpd.conf file.

Resource Limits

Although PHP’s resource-management capabilities were improved in version 5, you must still be careful to ensure that scripts do not monopolize server resources as a result of either programmer- or user-initiated actions. Three particular areas where such overconsumption is prevalent are script execution time, script input processing time, and memory. Each can be controlled via the following three directives.

max_execution_time = integer

Scope: PHP_INI_ALL; Default value: 30
The max_execution_time parameter places an upper limit on the amount of time, in seconds, that a PHP script can execute. Setting this parameter to 0 disables any maximum limit. Note that any time consumed by an external program executed by PHP commands, such as exec() and system(), does not count toward this limit.

max_input_time = integer

Scope: PHP_INI_ALL; Default value: 60
The max_input_time parameter places a limit on the amount of time, in seconds, that a PHP script devotes to parsing request data. This parameter is particularly important when you upload large files using PHP’s file upload feature, which is discussed in Chapter 15.

memory_limit = integerM

Scope: PHP_INI_ALL; Default value: 8M

The memory_limit parameter determines the maximum amount of memory, in megabytes, that can be allocated to a PHP script.

Data Handling

The parameters introduced in this section affect the way that PHP handles external variables— that is, variables passed into the script via some outside source. GET, POST, cookies, the operating system, and the server are all possible candidates for providing external data. Other parameters located in this section determine PHP’s default character set, PHP’s default MIME type, and whether external files will be automatically prepended or appended to PHP’s returned output.

arg_separator.output = string

Scope: PHP_INI_ALL; Default value: &amp;
PHP is capable of automatically generating URLs and uses the standard ampersand (&) to separate input variables. However, if you need to override this convention, you can do so by using the arg_separator.output directive.

arg_separator.input = string

Scope: PHP_INI_ALL; Default value: ;&
The ampersand (&) is the standard character used to separate input variables passed in via the POST or GET methods. Although unlikely, should you need to override this convention within your PHP applications, you can do so by using the arg_separator.input directive.

variables_order = string

Scope: PHP_INI_ALL; Default value: EGPCS
The variables_order directive determines the order in which the ENVIRONMENT, GET, POST, COOKIE, and SERVER variables are parsed. While seemingly irrelevant, if register_globals is enabled (not recommended), the ordering of these values could result in unexpected results due to later variables overwriting those parsed earlier in the process.

register_globals = On | Off

Scope: PHP_INI_SYSTEM; Default value: Off
If you have used a pre-4.0 version of PHP, the mere mention of this directive is enough to evoke gnashing of the teeth and pulling of the hair. To eliminate the problems, this directive was disabled by default in version 4.2.0 , but at the cost of forcing many long-time PHP users to entirely rethink (and in some cases rewrite) their Web application development methodology. This change, although done at a cost of considerable confusion, ultimately serves the best interests of developers in terms of greater application security. If you’re new to all of this, what’s the big deal?
Historically, all external variables were automatically registered in the global scope. That is, any incoming variable of the types COOKIE, ENVIRONMENT, GET, POST, and SERVER were made available globally. Because they were available globally, they were also globally modifiable. Although this might seem convenient to some people, it also introduced a security deficiency because variables intended to be managed solely by using a cookie could also potentially be modified via the URL. For example, suppose that a session identifier uniquely identifying the user is communicated across pages via a cookie. Nobody but that user should see the data that is ultimately mapped to the user identified by that session identifier. A user could open the cookie, copy the session identifier, and paste it onto the end of the URL, like this:

http://www.example.com/secretdata.php?sessionid=4x5bh5H793adK

The user could then e-mail this link to some other user. If there are no other security restrictions in place (e.g., IP identification), this second user will be able to see the otherwise confidential data. Disabling the register_globals directive prevents such behavior from occurring. While these external variables remain in the global scope, each must be referred to in conjunction with its type. For example, the sessionid variable in the previous example would instead be referred to solely as the following:

$_COOKIE['sessionid']

Any attempt to modify this parameter using any other means (e.g., GET or POST) causes a new variable in the global scope of that means ($_GET['sessionid'] or $_POST['sessionid']). In Chapter 3, the section on PHP’s superglobal variables offers a thorough introduction to external variables of the COOKIE, ENVIRONMENT, GET, POST, and SERVER types.
Although disabling register_globals is unequivocally a good idea, it isn’t the only factor you should keep in mind when you secure an application. Chapter 21 offers more information about PHP
application security.

■Note The register_globals feature has been a constant source of confusion and security-related problems
over the years. Accordingly, it is no longer available as of PHP 6.

register_long_arrays = On | Off

Scope: PHP_INI_SYSTEM; Default value: On
This directive determines whether to continue registering the various input arrays (ENVIRONMENT, GET,
POST, COOKIE, SYSTEM) using the deprecated syntax, such as HTTP_*_VARS. Disabling this directive is recommended for performance reasons.

■Note The register_long_arrays directive is no longer available as of PHP 6.

register_argc_argv = On | Off

Scope: PHP_INI_SYSTEM; Default value: On
Passing in variable information via the GET method is analogous to passing arguments to an executable. Many languages process such arguments in terms of argc and argv. argc is the argument count, and argv is an indexed array containing the arguments. If you would like to declare variables
$argc and $argv and mimic this functionality, enable register_argc_argv.

post_max_size = integerM

Scope: PHP_INI_SYSTEM; Default value: 8M
Of the two methods for passing data between requests, POST is better equipped to transport large amounts, such as what might be sent via a Web form. However, for both security and perfor- mance reasons, you might wish to place an upper ceiling on exactly how much data can be sent via this method to a PHP script; this can be accomplished using post_max_size.

WORKING WITH SINGLE AND DOUBLE QUOTES

Quotes, both of the single and double variety, have long played a special role in programming. Because they are commonly used both as string delimiters and in written language, you need a way to differentiate between the two in programming, to eliminate confusion. The solution is simple: escape any quote mark not intended to delimit the string. If you don’t do this, unexpected errors could occur. Consider the following:

$sentence = "John said, "I love racing cars!"";

Which quote marks are intended to delimit the string, and which are used to delimit John’s utterance? PHP
doesn’t know, unless certain quote marks are escaped, like this:

$sentence = "John said, \"I love racing cars!\"";

Escaping nondelimiting quote marks is known as enabling magic quotes. This process could be done either automatically, by enabling the directive magic_quotes_gpc (introduced in this section), or manually, by using the functions addslashes() and stripslashes(). The latter strategy is recommended because it enables you to wield total control over the application, although in those cases where you’re trying to use an application in which the automatic escaping of quotations is expected, you’ll need to enable this behavior accordingly.
Three parameters have long determined how PHP behaves in this regard: magic_quotes_gpc, magic_quotes_runtime, and magic_quotes_sybase. However, because this feature has long been a source of confusion among developers, it’s been removed as of PHP 6.

magic_quotes_gpc = On | Off

Scope: PHP_INI_SYSTEM; Default value: On
This parameter determines whether magic quotes are enabled for data transmitted via the GET, POST, and cookie methodologies. When enabled, all single and double quotes, backslashes, and null characters are automatically escaped with a backslash.

magic_quotes_runtime = On | Off

Scope: PHP_INI_ALL; Default value: Off
Enabling this parameter results in the automatic escaping (using a backslash) of any quote marks located within data returned from an external resource, such as a database or text file.

magic_quotes_sybase = On | Off

Scope: PHP_INI_ALL; Default value: Off
This parameter is only of interest if magic_quotes_runtime is enabled. If magic_quotes_sybase is enabled, all data returned from an external resource will be escaped using a single quote rather than a backslash. This is useful when the data is being returned from a Sybase database, which employs a rather unorthodox requirement of escaping special characters with a single quote rather than a backslash.

auto_prepend_file = string

Scope: PHP_INI_SYSTEM; Default value: NULL
Creating page header templates or including code libraries before a PHP script is executed is most commonly done using the include() or require() function. You can automate this process and forgo the inclusion of these functions within your scripts by assigning the file name and corresponding path to the auto_prepend_file directive.

auto_append_file = string

Scope: PHP_INI_SYSTEM; Default value: NULL
Automatically inserting footer templates after a PHP script is executed is most commonly done using the include() or require() functions. You can automate this process and forgo the inclusion of these functions within your scripts by assigning the template file name and corresponding path to the auto_append_file directive.

default_mimetype = string

Scope: PHP_INI_ALL; Default value: text/html
MIME types offer a standard means for classifying file types on the Internet. You can serve any of these file types via PHP applications, the most common of which is text/html. If you’re using PHP in other fashions, however, such as a content generator for WML (Wireless Markup Language) applications, you need to adjust the MIME type accordingly. You can do so by modifying the default_mimetype directive.

default_charset = string

Scope: PHP_INI_ALL; Default value: iso-8859-1
As of version 4.0, PHP outputs a character encoding in the Content-Type header. By default this is set to iso-8859-1, which supports languages such as English, Spanish, German, Italian, and Portuguese, among others. If your application is geared toward languages such as Japanese, Chinese,
or Hebrew, however, the default_charset directive allows you to update this character set setting accordingly.

always_populate_raw_post_data = On | Off

Scope: PHP_INI_PERDIR; Default value: On
Enabling the always_populate_raw_post_data directive causes PHP to assign a string consisting of POSTed name/value pairs to the variable $HTTP_RAW_POST_DATA, even if the form variable has no corresponding value. For example, suppose this directive is enabled and you create a form consisting of two text fields, one for the user’s name and another for the user’s e-mail address. In the resulting form action, you execute just one command:

echo $HTTP_RAW_POST_DATA;

Filling out neither field and clicking the Submit button results in the following output:

name=&email=

Filling out both fields and clicking the Submit button produces output similar to the following:

name=jason&email=jason%40example.com

Paths and Directories

This section introduces directives that determine PHP’s default path settings. These paths are used for including libraries and extensions, as well as for determining user Web directories and Web document roots.

include_path = string

Scope: PHP_INI_ALL; Default value: NULL
The path to which this parameter is set serves as the base path used by functions such as include(), require(), and fopen_with_path(). You can specify multiple directories by separating each with a semicolon, as shown in the following example:

include_path=".:/usr/local/include/php;/home/php"

By default, this parameter is set to the path defined by the environment variable PHP_INCLUDE_PATH. Note that on Windows, backward slashes are used in lieu of forward slashes, and the drive letter
prefaces the path:

include_path=".;C:\php6\includes"

doc_root = string

Scope: PHP_INI_SYSTEM; Default value: NULL
This parameter determines the default from which all PHP scripts will be served. This parameter is used only if it is not empty.

user_dir = string

Scope: PHP_INI_SYSTEM; Default value: NULL
The user_dir directive specifies the absolute directory PHP uses when opening files using the
/~username convention. For example, when user_dir is set to /home/users and a user attempts to open the file ~/gilmore/collections/books.txt, PHP knows that the absolute path is /home/ users/ gilmore/collections/books.txt.

extension_dir = string

Scope: PHP_INI_SYSTEM; Default value: ./
The extension_dir directive tells PHP where its loadable extensions (modules) are located. By default, this is set to ./, which means that the loadable extensions are located in the same directory as the executing script. In the Windows environment, if extension_dir is not set, it will default to C:\PHP-INSTALLATION-DIRECTORY\ext\. In the Linux environment, the exact location of this directory depends on several factors, although it’s quite likely that the location will be PHP-INSTALLATION- DIRECTORY/lib/php/extensions/no-debug-zts-RELEASE-BUILD-DATE/.

enable_dl = On | Off

Scope: PHP_INI_SYSTEM; Default value: On
The enable_dl() function allows a user to load a PHP extension at run time—that is, during a script’s execution.

Fopen Wrappers

This section contains five directives pertinent to the access and manipulation of remote files.

allow_url_fopen = On | Off

Scope: PHP_INI_ALL; Default value: On
Enabling allow_url_fopen allows PHP to treat remote files almost as if they were local. When enabled, a PHP script can access and modify files residing on remote servers, if the files have the correct permissions.

from = string

Scope: PHP_INI_ALL; Default value: NULL
The title of the from directive is perhaps misleading in that it actually determines the password, rather than the identity, of the anonymous user used to perform FTP connections. Therefore, if from is set like this

from = "jason@example.com"

the username anonymous and password jason@example.com will be passed to the server when authen- tication is requested.

user_agent = string

Scope: PHP_INI_ALL; Default value: NULL
PHP always sends a content header along with its processed output, including a user agent attribute. This directive determines the value of that attribute.

default_socket_timeout = integer

Scope: PHP_INI_ALL; Default value: 60
This directive determines the time-out value of a socket-based stream, in seconds.

auto_detect_line_endings = On | Off

Scope: PHP_INI_ALL; Default value: Off
One never-ending source of developer frustration is derived from the end-of-line (EOL) character because of the varying syntax employed by different operating systems. Enabling auto_detect_ line_endings determines whether the data read by fgets() and file() uses Macintosh, MS-DOS, or Linux file conventions.

Dynamic Extensions

This section contains a single directive, extension.

extension = string

Scope: PHP_INI_ALL; Default value: NULL
The extension directive is used to dynamically load a particular module. On the Win32 operating system, a module might be loaded like this:

extension = php_java.dll

On Unix, it would be loaded like this:

extension = php_java.so

Keep in mind that on either operating system, simply uncommenting or adding this line doesn’t necessarily enable the relevant extension. You’ll also need to ensure that the appropriate software is installed on the operating system. For example, to enable Java support, you also need to install the JDK.

Choosing a Code Editor

While there’s nothing wrong with getting started writing PHP scripts using no-frills editors such as Windows Notepad or vi, chances are you’re soon going to want to graduate to a full-fledged PHP- specific development solution. Several open source and commercial solutions are available.

Adobe Dreamweaver CS3

Formerly known as Macromedia Dreamweaver MX, Adobe’s Dreamweaver CS3 is considered by many to be the ultimate Web designer’s toolkit. Intended to be a one-stop application, Dreamweaver CS3 supports all of the key technologies, such as Ajax, CSS, HTML, JavaScript, PHP, and XML, which together drive cutting-edge Web sites.
In addition to allowing developers to create Web pages in WYSIWYG (what-you-see-is-what- you-get) fashion, Dreamweaver CS3 offers a number of convenient features for helping PHP developers more effectively write and manage code, including syntax highlighting, code completion, and the ability to easily save and reuse code snippets.
Adobe Dreamweaver CS3 (http://www.adobe.com/products/dreamweaver/) is available for the
Windows and Mac OS X platforms, and retails for $399.

■Tip If you settle upon Dreamweaver, consider picking up a copy of The Essential Guide to Dreamweaver CS3
with CSS, Ajax, and PHP by David Powers (friends of ED, 2007). Learn more about the book at http://www. friendsofed.com/.

Notepad++

Notepad++ is a mature open source code editor and avowed Notepad replacement available for the Windows platform. Translated into 41 languages, Notepad++ offers a wide array of convenient features one would expect of any capable IDE, including the ability to bookmark specific lines of a document for easy reference; syntax, brace, and indentation highlighting; powerful search facilities; macro recording for tedious tasks such as inserting templated comments; and much more.
PHP-specific support is fairly slim, with much of the convenience coming from the general
features. However, rudimentary support for auto-completion of function names is offered, which will cut down on some typing, although you’re still left to your own devices regarding remembering parameter names and ordering.
Notepad++ is only available for the Windows platform and is released under the GNU GPL. Learn more about it and download it at http://notepad-plus.sourceforge.net/.

PDT (PHP Development Tools)

The PDT project (http://www.eclipse.org/pdt/) is currently seeing quite a bit of momentum. Backed by leading PHP products and services provider Zend Technologies Ltd. (http://www.zend.com/), and built on top of the open source Eclipse platform (http://www.eclipse.org/), a wildly popular extensible framework used for building development tools, PDT is the likely front-runner to become the de facto PHP IDE for hobbyists and professionals alike.

■Note The Eclipse framework has been the basis for a wide array of projects facilitating crucial development tasks such as data modeling, business intelligence and reporting, testing and performance monitoring, and, most notably, writing code. While Eclipse is best known for its Java IDE, it also has IDEs for languages such as C, C++, Cobol, and more recently PHP.

Zend Studio

Zend Studio is far and away the most powerful PHP IDE of all commercial and open source offerings available today. A flagship product of leading PHP products and services provider Zend Technologies Ltd., Zend Studio offers all of the features one would expect of an enterprise IDE, including compre- hensive code completion, CVS and Subversion integration, internal and remote debugging, code profiling, and convenient code deployment processes.
Facilities integrating code with popular databases such as MySQL, Oracle, PostgreSQL, and SQLite are also offered, in addition to the ability to execute SQL queries and view and manage data- base schemas and data.
Zend Studio (http://www.zend.com/products/zend_studio/) is available for the Windows, Linux, and Mac OS X platforms in two editions: standard and professional. The Standard Edition lacks key features such as database, CVS/Subversion, and Web Services integration but retails at just $99. The Professional Edition offers all of the aforementioned features and more and retails at $299.

Choosing a Web Hosting Provider

Unless you work with an organization that already has an established Web site hosting environment, eventually you’re going to have to evaluate and purchase the services of a Web hosting provider. Thankfully this is an extremely crowded and competitive market, with providers vying for your busi- ness, often by offering an impressive array of services, disk space, and bandwidth at very low prices.
Generally speaking, hosting providers can be broken into three categories:

• Dedicated server hosting: Dedicated server hosting involves leasing an entire Web server, allowing your Web site full reign over server CPU, disk space, and memory resources, as well as control over how the server is configured. This solution is particularly advantageous because you typically have complete control over the server’s administration while not having to purchase or maintain the server hardware, hosting facility, or the network connection.
• Shared server hosting: If your Web site will require modest server resources, or if you don’t want to be bothered with managing the server, shared server hosting is likely the ideal solu- tion. Shared hosting providers capitalize on these factors by hosting numerous Web sites on a single server and using highly automated processes to manage system and network resources, data backups, and user support. The result is that they’re able to offer appealing pricing arrangements (many respected shared hosting providers offer no-contract monthly rates for as low as $8 a month) while simultaneously maintaining high customer satisfaction.
• Virtual private server hosting: A virtual private server blurs the line between a dedicated and shared server, providing each user with a dedicated operating system and the ability to install applications and fully manage the server by way of virtualization. Virtualization provides a way to run multiple distinct operating systems on the same server. The result is complete control for the user while simultaneously allowing the hosting provider to keep costs low and pass those savings along to the user.

Keep in mind this isn’t necessarily a high-priority task; there’s no need to purchase Web hosting services until you’re ready to deploy your Web site. Therefore, even in spite of the trivial hosting rates, consider saving some time, money, and distraction by waiting to evaluate these services until absolutely necessary.

Seven Questions for Any Prospective Hosting Provider

On the surface, most Web hosting providers offer a seemingly identical array of offerings, boasting absurd amounts of disk space, endless bandwidth, and impressive guaranteed server uptimes. Frankly, chances are that any respected hosting provider is going to meet and even surpass your expecta- tions, not only in terms of its ability to meet the resource requirements of your Web site, but also in terms of its technical support services. However, as a PHP developer, there are several questions you should ask before settling upon a provider:

1. Is PHP supported, and if so, what versions are available? Many hosting providers have been aggravatingly slow to upgrade to the latest PHP version, with many still offering only PHP 4, despite PHP 5 having been released more than three years ago. Chances are it will take at least as long for most to upgrade to PHP 6, therefore, if you’re planning on taking advantage of version-specific features, be sure the candidate provider supports the appropriate version. Further, it would be particularly ideal if the provider simultaneously supported multiple PHP versions, allowing you to take advantage of various PHP applications that have yet to support the latest PHP version.
2. Is MySQL/Oracle/PostgreSQL supported, and if so, what versions are available? Like PHP, hosting providers have historically been slow to upgrade to the latest database version. Therefore, if you require features available only as of a certain version, be sure to confirm that the provider supports that version.
3. What PHP file extensions are supported? Inexplicably, some hosting providers continue to demand users use deprecated file extensions such as .php3 for PHP-enabled scripts, despite having upgraded their servers to PHP version 4 or newer. This is an indicator of the provider’s lack of understanding regarding the PHP language and community and therefore you should avoid such a provider. Only providers allowing the standard .php extension should be considered.
4. What restrictions are placed on PHP-enabled scripts? As you learned earlier in this chapter, PHP’s behavior and capabilities can be controlled through the php.ini file. Some of these configuration features were put into place for the convenience of hosting providers, who may not always want to grant all of PHP’s power to its users. Accordingly, some functions and extensions may be disabled, which could ultimately affect what features you’ll be able to offer on your Web site.
Additionally, some providers demand all PHP-enabled scripts are placed in a designated directory, which can be tremendously inconvenient and of questionable advantage in terms of security considerations. Ideally, the provider will allow you to place your PHP-enabled scripts wherever you please within the designated account directory.
5. What restrictions are placed on using Apache .htaccess files? Some third-party software, most notably Web frameworks (see Chapter 25), require that a feature known as URL rewriting be enabled in order to properly function; however, not all hosting providers allow users to tweak Apache’s behavior through special configuration files known as .htaccess files. Therefore, know what limitations, if any, are placed on their use.

6. What PHP software do you offer by default, and do you support it? Most hosting providers offer automated installers for installing popular third-party software such as Joomla!, WordPress, and phpBB. Using these installers will save you some time, and will help the hosting provider troubleshoot any problems that might arise. However, be wary that some providers only offer this software for reasons of convenience and will not offer technical assistance. Therefore, be prepared to do your own homework should you have questions or encounter problems using third-party software. Additionally, you should ask whether the provider will install PEAR and PECL extensions upon request (see Chapter 11).
7. Does (insert favorite Web framework or technology here) work properly on your servers?
If you’re planning on using a particular PHP-powered Web framework (see Chapter 25 for more information about frameworks) or a specific technology (e.g., a third-party e-commerce solution), you should take care to make sure this software works properly on the hosting pro- vider’s servers. If the hosting provider can’t offer a definitive answer, search various online forums using the technology name and the hosting provider as keywords.

Summary

In this chapter you learned how to configure your environment to support the development of PHP- driven Web applications. Special attention was given to PHP’s many run-time configuration options. Finally, you were presented with a brief overview of the most commonly used PHP editors and IDEs, in addition to some insight into what to keep in mind when searching for a Web hosting provider.
In the next chapter, you’ll begin your foray into the PHP language by creating your first PHP- driven Web page and learning about the language’s fundamental features. By its conclusion, you’ll be able to create simplistic yet quite useful scripts. This material sets the stage for subsequent chapters, where you’ll gain the knowledge required to start building some really cool applications.

0 comments: