Including and Requiring Files
As you progress in your use of PHP programming, you are likely to start building a library of functions that you think you will need again. You’ll also probably start using libraries created by other programmers.
There’s no need to copy and paste these functions into your code. You can save them in separate files and use commands to pull them in. There are two types of commands to perform this action: include and require.
The include Statement
Using include, you can tell PHP to fetch a particular file and load all its contents. It’s as if you pasted the included file into the current file at the insertion point.
<?php include "anyfile.php"; // Your code goes here ?>
Each time you issue the include directive, it includes the requested file again, even if you’ve already inserted it. For instance, suppose that library.php contains a lot of useful functions, so you include it in your file, but also include another library that includes library.php. Through nesting, you’ve inadvertently included library.php twice. This will produce error messages, because you’re trying to define the same constant or function
multiple times. So you should use include_once instead.
<?php include_once "anyfile.php"; // Your code goes here ?>
In general, it’s probably best to stick with include_once and ignore the basic include statement. That way you will never have the problem of
files being included multiple times.
Using require and require_once
A potential problem with include and include_once is that PHP will only attempt to include the requested file. Program execution continues even if the file is not found. When it is absolutely essential to include a file, require it. For the same reasons I gave for using include_once, I recommend that you generally stick with require_once whenever you need to require a file.
<?php require_once "anyfile.php"; // Your code goes here ?>