PHP control structure comprises with several type of statements. In this article, we are going to compare the include() and require() statements and their _once usage. These statements are used to add the script from external file.
So the PHP files are embedded into one another in various ways based on the the following PHP functions.
For all the above functions, we need to specify file path to be embedded. This path might be either of an absolute path or of an relative path. Let us see about the functions one by one in following discussion.
This function is used to include a external file into a php file. The syntax of include statement as follows.
<?php include("../file_name.php"); // relative path //OR include("/xampp/hddocs/file_name.php"); // absolute path
We should any one of the above staements. Because more than one attempt of adding include statement will return error like as follows, if the target file has the code for function declaration.
Fatal error: Cannot redeclare...
If the target file is not exist, then the warning notice will be created as,
Warning: failed to open stream: No such file or directory... Warning: Failed opening ... for inclusion...
This function will perform in strict manner where it wont allow program for further execution, if the requited target file is not exist. Instead of warning notice created by the include(), this will generate error like as shown below.
Warning: failed to open stream: No such file or directory... Fatal error: Failed opening required...
Syntax of this statement is,
<?php require("../file_name.php"); // relative path //OR require("/xampp/hddocs/file_name.php"); // absolute path
This function also wont allow the multiple attempts of adding require statement for the same file as like as include() function.
Both are similar to the include() and require(), respectively. The only difference is that these statements wont return any error message on attempting to include the same file more than once. Rather, the _once usage will check, if the target file is included already. If not, the file will be included, otherwise, the execution will skip to next statement. And the syntax of these statements are shown as below.
<?php include_once("../file_name.php"); // relative path
<?php require_once("../file_name.php"); // relative path
In older versions of PHP, include() was used to embed external file conditionally where as require() will refer target file as a resource.
This PHP code tutorial was published on April 22, 2013.