Using Include Files in Practice

Example 4-7 and Example 4-8 show the two files included with the include directive in Example 4-6. As discussed in Chapter 2, the include directive allows common functions in other files to be accessible from within the body of a script without directly adding the functions to the code.

Example 4-7. The include file
   $hostName = "localhost";
   $databaseName = "winestore";
   $username = "fred";
   $password = "shhh";
Example 4-8. The include file
   function showerror(  )
      die("Error " . mysql_errno(  ) . " : " . mysql_error(  ));

Both include files are added to all code developed for the winestore and allow easy adjustment of the database server name, database name, and DBMS username and password. The flexibility to adjust these parameters in a central location allows testing of the system on a backup or remote copy of the data, by changing the database name or hostname in one file. This approach also allows the use of different username and password combinations with different privileges, for testing purposes.

We have chosen to name our include files with the .inc extension. This presents a minor security problem. If the user requests the include file, the source of the include file is shown in the browser. This may expose the username and password for the DBMS, the source code, the database structure, and other details that should be secure.

There are three ways to address this problem. First, you can store the include files outside the document tree of the Apache web server installation. For example, store the include files in the directory /usr/local/include/php and use the complete path in the include directive. Second, you can use the extension .php instead of .inc. In this case, the include file is processed by the PHP script engine and produces no output because it contains no main body. Third, you can configure Apache so that files with the extension .inc are forbidden to be retrieved.

All three approaches to securing include files work effectively in practice. Using the extension .php for include files is the simplest solution but has the disadvantage that includes files can't be easily distinguished from other files. In the online winestore, we have configured Apache to disallow retrieval of files with the extension .inc.