In PHP, there are four functions available for including files: include(), require(), include_once(), and require_once(). These functions are used to include and evaluate the contents of PHP files within other PHP files. Here's a summary of each function:
1. include():
The include() function is used to include and evaluate a specified file during script execution.
If the file cannot be found or there is an error during inclusion, a warning is issued, but the script continues to execute.
Multiple include() statements for the same file can be used, and the file will be included each time.
Example: include 'filename.php';
2. require():
The require() function is similar to include(), but it has stricter error handling behavior.
If the file cannot be found or there is an error during inclusion, a fatal error is issued, and the script execution is halted.
Multiple require() statements for the same file can be used, and the file will be included each time.
Example: require 'filename.php';
3. include_once():
The include_once() function includes and evaluates a specified file, but only if it has not been previously included in the script.
If the file has already been included, it is skipped, and the script continues to execute.
Multiple include_once() statements for the same file can be used, but the file will be included only once.
Example: include_once 'filename.php';
4. require_once():
The require_once() function is similar to include_once(), but with stricter error handling behavior.
If the file has already been included, it is skipped, and the script continues to execute.
If the file cannot be found or there is an error during inclusion, a fatal error is issued, and the script execution is halted.
Multiple require_once() statements for the same file can be used, but the file will be included only once.
Example: require_once 'filename.php';
The choice between include()/require() and include_once()/require_once() depends on the specific needs of your code. If you need to include a file multiple times or the file is optional, you can use include() or require(). If you want to ensure that a file is included only once, you can use include_once() or require_once().
It's important to note that including files using any of these functions should be done with caution, especially when including files based on user input. You should validate and sanitize any file paths before using them in these functions to prevent potential security vulnerabilities such as directory traversal attacks.