In this tutorial, we are going to see the list of functions used in PHP to include external file into a program. PHP provides various functions to include external files.
It is required if the current code dependency is on the external file to be included. For example, if we want to create an instance of a class defined in the separate class file, then it has to be included before creating an instance of it.
The following list of functions is used to include external file into a PHP program. In this tutorial, we are going to compare these functions with suitable examples.
Also, we are going to see the purpose of the _once usage and the difference between include and include_once/require and require_once.
PHP include() function includes external file into a PHP program. It accepts the external file path and checks if the file exists or not. If the file does not exist in the specified path, then the include() will return PHP warning.
Warning: failed to open stream: No such file or directory... Warning: Failed opening ... for inclusion...
By including an external file by using the PHP include() function, the variable, functions, and classes of the included file can be used in the program where it is included. The following code shows an example for including an external file using PHP include().
<?php include("../file_name.php"); // relative path //OR include("/xampp/hddocs/file_name.php"); // absolute path
If we include the same file multiple time by using this function, then it will cause a PHP error.
PHP require() function is as similar as include() function. But, the difference is, the require() function will return a fatal error and stop executing the program at the time of failure where the include() function returns warning and continue execution.
Warning: failed to open stream: No such file or directory... Fatal error: Failed opening required...
The code to include file using require() function is,
<?php require("../file_name.php"); // relative path //OR require("/xampp/hddocs/file_name.php"); // absolute path
The include_once() and require_once() functions are similar to the include() and require() functions, respectively. But, using this function will create difference at the time of including the same file for multiple time.
By using include_once() and require_once() functions, will include the specified file if it is not already included, otherwise, PHP will ignore this statement. The code is,
<?php include_once("../file_name.php"); // relative path
<?php require_once("../file_name.php"); // relative path