Although it's not ever truly necessary, many times it is important to have the ability to separate PHP code into multiple files to ease organization and promote the idea of reusing common functions within your PHP programs.
Thankfully, PHP supports four different language constructs and functions to allow for the import of code from other files.
Including Code in Your PHP Script
There are many ways to include code in PHP. Depending on your system's configuration, you can include files from both your local file system or even from remote servers that are configured to do so. There are many different tricks and useful ways to use this behavior in PHP and I'll try to cover most of them here.
The most basic of all code imports in PHP can be done with the use of PHP's include() statement. The syntax for the include statement is as follows:
include '<path or URL to the file to include>';
When an include statement is encountered by PHP, the PHP engine immediately stops parsing PHP code and attempts to import the code directly over the calling include statement. This means that whatever code is contained within the requested file will replace the include statement and will have available to it any variables that were defined, as well as be constrained to the same variable scope. Furthermore, any PHP code that is included must also be wrapped in standard PHP code tags such as <?php and ?>.
Here's an example. Below are two different files. The first file, myscript.php is the file that has been executed by PHP initially. The second file, included.php is another PHP script that is meant to be included:
script.php
| <?php for($i = 0; $i < 10; $i ++) { include 'include_file.php'; } if(isset($testvar)) echo '$testvar is set<br />'; ?> |
include_file.php
| <b><u> <?php echo 'The value of the variable is: $i<br />'; ?> </u></b> >?php $test = true; ?< |
In the above example, assuming that the file included.php is in the same directory as script.php, the output will be:
The value of the variable is: 0
The value of the variable is: 1
to...
The value of the variable is: 9
$testvar is set
Notice that the $i variable was not defined anywhere in the include_file.php script where it is used; instead it has been automatically inherited from the calling script.
Note: The above output is not in error. Because the above script uses single quotes instead of double quotes to check for the existence of $test in the final echo statement, it will be displayed to the client as is, and the output will reflect the string '$test' instead of the value contained within the PHP variable of the same name.
Returning Values
At times, it may be beneficial to return a value from within the include statement back to the original calling script. To accomplish this, you may simply place a return statement within the include file but outside of any functions defined within the included file. The returned value will be the result value of the include statement that initiated the inclusion of the file, as shown below:
script.php
| <?php $returnval = include 'include_file2.inc'; echo "The file include_file2.inc returned a value of '$returnval'<br />"; $returnval = include 'include_file3.inc'; echo "The file include_file3.inc returned a value of '$returnval'<br />"; ?> |
include_file2.inc
| <?php return 'testing'; ?> |
include_file3.inc
| <?php echo "Hello, world!<br />"; ?> |
The result of the above code executing would be:
The file include_file2.inc returned a value of 'testing'
Hello, world!
The file include_file3.inc returned a value of '1'
Note that if the included file returns no value the include statement will return true upon success or false upon failure.
Ensuring Files Are Only Included Once
In the above script, you'll notice that we used the include statement to include the same file over and over, each time producing a different result. Sometimes, such as when the file desired to be included as a function definition within it, it is important that the file be included once and only once. Although there are ways to ensure this with a standard include statement PHP provides the means to accomplish this very cleanly by using the statement include_once instead of simply include. The include_once statement behaves identically to its sister statement include with the single difference that PHP will not include the file multiple times. It is recommended that this version of the include statement be used in situations where included files contain function declarations or other code that should not be executed numerous times.
A Note on Errors Occurring with Include Files
One important thing to note regarding the include and include_once statements is how PHP handles errors that occur either loading them, or during the process of executing the code within them. In the event of an error during an include statement's execution, PHP will generate a error of type E_NOTICE and continue execution of the script. How this error is presented to the user depends on the configuration settings of PHP. If the included file is critical to the script's operation, you'll need to use the require statement described below.
Forcing Files to Be Included
As I've discussed, errors that occur during the inclusion or executions of included files using the include or include_once statements will cause the trigger of an E_NOTICE error and return false. Because this error is not considered fatal by PHP scripts, the desired file simply will not be included and script execution will continue. In situations where the code contained within the include file was required, this will produce unpredictable results. To combat this, PHP provides another similar way of including files: the require and require_once statements.
In versions of PHP prior to 4.0.2, the require statement behaved differently than its counterpart include in both the way and at what time files were included. In versions of PHP above 4.0.2, require now behaves almost identically to include. The only difference is in what PHP does in case of an error. If an error occurs during the execution of a require or require_once statement, it will trigger a fatal error of type E_ERROR resulting in the entire script execution halting. This behavior is most desired when the included code is critical to the general function of the entire script, such as the setting of critical variables or the definition of functions that are used within the calling script. As with include_once, require_once will ensure that the requested file is included in the PHP script only once.
Related Articles
- PHP and Web DesignNote 1: You dont have to know PHP programming to do this tutorial. Note 2: I assume that your server supports files with .php extension. If not, you wont be able to do this tutorial. For more info on how to install PHP on your PC go to Php.net...
- Auto RedirectNote 1: You dont have to know PHP programming to do this tutorial. Note 2: I assume that your server supports files with .php extension. If not, you wont be able to do this tutorial. For more info on how to install PHP on your PC go to Php.net...
- Web Hosting and Types of Web HostingWhile most of us can design a website and upload any information, news, bulletins, images, files and documents (incl. HTML files, CSS files, graphic files, java scripts etc.), to make the same available for public viewing we need to copy the site to a public server....
- 4 Powerful Features of Javascript Programming LanguageIn the community of web developers and surfers, Javascript is highly popular as client side scripting language for web browsers. Lets take a look at some of the features of this language.
- Introduction to Procedural ProgrammingWell start of with if
Here is the basic usage of it
variable would be something like $variable - Alternating Row ColorsTheres two different ways this can be done. The first is by getting results from a mysql query, the second is going through the values of an array. Ill go over both. First the full files (ill break it up into two files, one using mysql, and one using an array)
- Prevent Directory ListingWhenever you have folders with large amounts of files or important administration files, it is essential to prevent directory listings, otherwise all of the files in the folder will be listed to anyone who wants to see them, including hackers. When hackers can find an administration file, it makes t...
- 11 Things to Check Before Purchasing Web HostingThe web hosting industry is extremely competitive due to the fact of the massive growth of the internet and the fact that people want to have their own website....
- 3 Ways To Backup Your WebsiteData loss is the worst nightmare of people who own precious computer files, whether he is a website administrator or just a simple e-mail user. Sometimes, just one wrong push of a button can make all your files instantly vanish without a trace.
- Uploading Files With PHPUpload an image or file to your server without using your FTP.
