Article
The PHP Anthology Volume 1, Chapter 1 - PHP Basics
How do I include one PHP script in another?
Having discovered that writing thousand-line scripts may not be the best way to stay organized, you're probably looking for ways to break your code into separate files. Perhaps, while using someone else's Open Source application, you find yourself struggling to eliminate error messages like the one below:
Fatal error: Failed opening required 'script.php'
Mutual Inclusion
PHP provides four commands that allow you to add the contents of one PHP script to another, namely include, require, include_once and require_once. In each case, PHP fetches the file named in the command, then executes its contents. The difference between include and require is the way they behave should they be unable to find the script they were told to fetch.
include will generate a PHP warning message like this:
Warning: Failed opening 'script.php' for inclusion
This will allow the script that called the include command to continue execution.
By contrast, require results in a fatal error like the one shown above, which means the calling script will terminate, bringing everything to a halt. If the file that was required is critical to your application, having the script terminate is a very good thing.
The include_once and require_once commands behave similarly to their respective cousins, but if the script has already been included or required anywhere else (by any of the four commands), the statement will be ignored. At first glance, it may not be obvious how these commands can be used; surely you'll know how many times you've used an include command, right? Where the _once commands become extremely handy is in more complex applications in which you have PHP scripts that include other PHP scripts, which in turn include yet more PHP scripts. This is particularly important when you use libraries of classes (which we'll explore in Chapter 2, Object Oriented PHP), and those classes are being reused repeatedly by many scripts. One class may depend on another being available; using a require_once to include the required class ensures it will always be available, yet causes no problem if the class happens to have been used elsewhere.
To see all this in action, let's make a script called include_me.php:
Example 1.5. include_me.php
<?php
// include_me.php
echo 'I\'ve been included!<br />';
?>
Every time this script is included it will display the message "I've been included!" so we know it's worked.
Now, let's test the various ways we can include this file in another script:
Example 1.6. 5.php
<?php
// This works fine
echo '<br />Requiring Once: ';
require_once 'include_me.php';
// This works fine as well
echo '<br />Including: ';
include 'include_me.php';
// Nothing happens as file is already included
echo '<br />Including Once: ';
include_once 'include_me.php';
// This is fine
echo '<br />Requiring: ';
require 'include_me.php';
// Again nothing happens - the file is included
echo '<br />Requiring Once again: ';
require_once 'include_me.php';
// Produces a warning message as the file doesn't exist
echo '<br />Include the wrong file: ';
include 'include_wrong.php';
// Produces a fatal error and script execution halts
echo '<br />Requiring the wrong file: ';
require 'include_wrong.php';
// This will never be executed as we have a fatal error
echo '<br />Including again: ';
include 'include_me.php';
?>
Here's the output this generates (note that I've simplified the error messages at the end):
Requiring Once: I've been included!
Including: I've been included!
Including Once:
Requiring: I've been included!
Requiring Once again:
Include the wrong file:
Warning: Failed opening 'include_wrong.php' for inclusion
Requiring the wrong file:Fatal error: Failed opening required
'include_wrong.php'
Notice here that the first use of include_once does nothing (the file has already been included), as does the later use of require_once. Later on, when I try to include the wrong file (in this case, a file that doesn't exist), I get a warning message. However, execution continues to the next line where I try to require a file that doesn't exist. This time, PHP produces a fatal error and execution of the script halts, meaning the final attempt to include the file will never happen.
Be aware that the files you include needn't contain only PHP. The included file could simply contain HTML without any PHP.
Which Command to Use?
As a general practice, unless you have a special circumstance where some other behavior is needed, always use the require_once command to include one file in another. This is particularly important when you're placing PHP classes in separate files, and one class may depend on another. For the full story on classes, see Chapter 2, Object Oriented PHP.
PHP's four include commands should not be confused with the various file-related functions (discussed in Chapter 4, Files); these are intended for fetching files without parsing them immediately as PHP scripts, thereby allowing you to work on their contents.
Note that throughout this book I'll be talking about "including" a file even when I'm using one of the require commands. This is a common convention for talking about PHP that stems from older programming languages used by the first PHP pioneers.
Path Finding
So far, I've only looked at including files in the same directory as the script that contains the include command. In practice, you'll usually want to organize files into subdirectories based on the job they do. This can be a source of much confusion, particularly when you're using third party code, as there are numerous alternative approaches to dealing with includes in other directories.
The first thing to be aware of is that all includes are calculated relative to the directory in which the main script (where execution began) resides. For example, imagine we have three files in the following locations:
/home/username/www/index.php
/home/username/www/includes/script.php
/home/username/www/another.php
First, let's consider index.php. The command include 'includes/script.php'; will correctly include script.php, assuming index.php is the actual file requested.
But what if we use the following command in script.php:
include '../another.php'; // ???
If script.php is the page we're viewing, this command will correctly include another.php. However, if index.php is the page we're viewing, and it includes script.php, this command will fail, because the location of another.php is calculated relative to the location of index.php, not relative to script.php.
We have two choices. We can modify script.php so that it includes another.php as follows:
include 'another.php';
Alternatively, we can enter the full path to another.php, like this:
include '/home/username/www/another.php';
This leaves no doubt as to where another.php is located.
The PHP configuration file php.ini also contains the directive include_path. This allows you to specify directories from which files can be included, without the need to specify their locations when using one of the include commands.
This approach needs to be used with caution, as it may lead to strange results if an included file of the same name exists in more than one directory, yet it can be an effective means to solve include-related headaches. PHP's PEAR class library, for example, relies on your adding the directory that contains PEAR's include files to the include path. Note also that it's not a good idea to specify too many locations in your include path, as this will slow PHP down when it tries to find the scripts you've included in your code.
If you're using Apache in a shared hosting environment, you may be able to override the value of include_path using a .htaccess file. Placed in the directory to which you want it to apply (it will also apply to all subdirectories), the file should contain something like this:
php_value include_path ".:/usr/local/lib/php:/home/user/phplib/"
The same can also be accomplished with the PHP function ini_set, for example:
ini_set('include_path', 'C:/phplib/');
This allows changes to be made at runtime from within a PHP script.
You'll find a reference to php.ini values in Appendix A, PHP Configuration.