We already learned about including files in PHP in
PHP | (Include and Require) . We discussed the include() and require() functions for including files in our previous article. In this article, we will discuss two more useful functions in PHP for including files: the include_once() and require_once() functions.
include_once() function The include_once() function can be used to include a PHP file in another file when you may need to include the called file more than once. If it detects that the file has already been included, the calling script will ignore any further include.If the file named
a.php is a php script calling
b. php with
function include_once(), and does not find
b.php,
a.php is executed with a warning, excluding part of the code, written in
b.php.
Syntax:include_once (’name of the called file with path’);
Example:
// file name is header.inc.php
echo
"GEEKSFORGEEKS"
;
?>
The above file is header.inc.php The above header.inc.php file is included twice by the include_once() function in the following index.php file. But from the output, you get that the second instance of the include is ignored, because the include_once() function ignores all such inclusions after the first. // file name index.php
include_once
(
’header.inc.php’
);
include_once
(
’ header.inc.php’
);
?>
Output:GEEKSFORGEEKS
The require_once() function The require_once() function can be used to include a PHP file in another file when you may need to include the called file more than once ... If it detects that the file has already been included, the calling script will ignore any further include.If a.php - this is a php script that calls b.php with function require_once() and does not find b.php, a.php stops execution, causing a fatal error. Syntax:require_once (’name of the called file with path ’);
Example: // file name is header.inc.php
echo
"GEEKSFORGEEKS"
;
?>
The above file is header.inc.php The above header.inc.php file is included twice with the require_once() function in the following index.php file. But from the output, you get that the second instance of the include is ignored, since the require_once() function ignores all such include after the first. // file name index.php
require_once
(
’header.inc.php’
);
require_once
(
’ header.inc.php’
);
?>
Output:GEEKSFORGEEKS
include_once() versus require_once() Both functions work the same and produce the same output, but if any error occurs then differences arise.Example :If we don’t have a file named header.inc.php, then in the case of include_once(), the output will be shown with warnings about missing file, but at least the output will be shown from the index.php file,In the case of require_once(), if the PHP file is missing, a fatal error will occur and no output will be displayed and execution will stop.