Why is this an issue?
At root, require
, require_once
, include
, and include_once
all perform the same task of
including one file in another. However, the way they perform that task differs, and they should not be used interchangeably.
-
require
includes a file but generates a fatal error if an error occurs in the process.
-
include
also includes a file, but generates only a warning if an error occurs.
Predictably, the difference between require
and require_once
is the same as the difference between include
and include_once
. The _once
versions ensure that the specified file is only included once.
What is the potential impact?
Including the same file multiple times could have unpredictable results, the _once
versions are preferred. Additionally, as
include_once
generates only warnings, it should be used only when the file is being included conditionally, i.e. when all possible error
conditions have been checked beforehand.
How to fix it
Rewrite your code to only contain require_once
and conditional include_once
calls.
Code examples
Noncompliant code example
include 'code.php'; //Noncompliant; not a "_once" usage and not conditional
include $user.'_history.php'; // Noncompliant
require 'more_code.php'; // Noncompliant; not a "_once" usage
Compliant solution
require_once 'code.php';
if (is_member($user)) {
include_once $user.'_history.php';
}
require_once 'more_code.php';
Resources
Documentation