The include_once and require_once statements in PHP work similarly to the include and require statements. The key difference is that these functions ensure the specified file is included only once, regardless of how many times the statement is called in the script.
include_once – Includes the file only once. If the file has already been included, it will not be included again.require_once – Includes the file only once, but stops script execution if the file cannot be found.Both statements prevent duplicate file loading, which helps avoid function redeclaration errors and repeated variable definitions.
// Including header.php only once even if called multiple times
<?php
include_once 'header.php';
include_once 'header.php';
echo "This is the body of the page.";
?>
The file header.php is included only once, preventing duplicate HTML output or PHP errors.
// require_once stops execution if config.php is missing
<?php
require_once 'config.php';
require_once 'config.php';
echo "This is the body of the page.";
?>
If config.php is missing, PHP throws a fatal error and stops execution immediately.
// Loading reusable functions safely with require_once
<?php
require_once 'functions.php';
require_once 'functions.php';
greetUser("Meghraj");
?>
require_once for mandatory files like configs.include_once for optional components.require_once for a missing file and observe the error.include_once._once and comparing behavior.