How to include other files in PHP 8
include expression allows you to evaluate other PHP files. Depending on the location expressed by the provided string,
include will look for the file in different locations.
include has sibling functions that behave similarly. See the list below:
include in PHP 8
If you want to include another file in PHP, there are several cases that you have to look out for. Generally speaking, you can divide
include's behavior into 4 cases.
- an absolute path
- a path which corresponds to a file in the
- a relative path which corresponds to a file in the calling script's directory
- a relative path which corresponds to a file in the current working directory
If the specified file can not be found, PHP 8 will emit an
E_WARNING. In case PHP's current instance can't access the file, an additional warning will precede the previously mentioned
After PHP has found the file and can access it, PHP will try to evalute it. The code executed by PHP will inherit the current variable scope at which the
include expression is called from. The callee's script will receive global access to all functions and classes within the included file.
To illustrate usuage patterns, the
include expression can occure at any location where you could call a function. This includes the global scope of a script, a function body, the body of an if clause, or even as part of the boolean expression of an if block.
include expression returns
1 on success or
FALSE on failure.
$result = include '/file/location';
Include a url
Alternatively, PHP can include a remote file by issuing an HTTP request. However, the behavior is slightly different from the file based version as 2 separate code executions could happen. First, the file is generated and run on the target server. The returned result will be reinterpreted with the current variable scrope if it contains a valid PHP script.
You have to pay special attention to only call trusted target servers as this use case has various potential security risks which you have to avoid. If you don't need to evaluate the result of the remote server, you are served better with the
<?php $size = 'small'; $furniture = 'chair'; ?>
<?php echo "You just bought a $size $furniture\n"; include 'variables.php'; echo "You just bought a $size $furniture"; ?>
You just bought a You just bought a small chair
In the example above, you can see two scripts. The first defines 2 variables. In the second script, we try to output the content of the variables of the first script twice. The first call fails, as the variable haven't been defined yet. After the include expression, the second try succeeds by correctly outputting the content of the