This question already has answers here:
Difference between "include" and "require" in php
(7 answers)
Closed 8 years ago.
I want to know when I should use include or require and what's the advantage of each one.
require requires, include includes.
According to the manual:
require() is identical to include() except upon failure it will produce a fatal E_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue.
As others have said, if "require" doesn't find the file it's looking for, execution will halt. If include doesn't file the file it's looking for, execution will continue.
In general, require should be used when importing code/class/function libraries. If you attempt to call a function, instantiate a class, etc. and the definitions aren't there, Bad Things will happen. Therefore, you require php to include your file, and if it can't, you stop.
Use include when you're using PHP to output content or otherwise execute code that, if it doesn't run, won't necessarily destroy later code. The classic example of this is implementing a View in a Model/View/Controller framework. Nothing new should be defined in a view, nor should it change application state. Therefore, it's ok to use include, because a failure won't break other things happening in the application.
One small tangent. There's a lot of conflicting information and mis-information out there regarding performance of include vs. require vs. require_once vs. include_once. They perform radically different under different situations/use-cases. This is one of those places where you really need to benchmark the difference in your own application.
The difference is this:
include will not fail if it cannot find the resource, require will. Honestly, it's kind of silly that include exists at all, because if you are attempting to load a resource you are pretty much counting on it being there. If you are going to use anything, I would recommend using require_once always, that way you don't run into collisions (ie, if another script is requiring the same file) and your code always works as intended because you know the resources you are including are there (otherwise it is failing).
If a file is optional, include it. For example, you might have a file 'breaking-news.txt' that gets created when there's breaking news, but doesn't exist when there's none. It could be included without the script breaking if there's no breaking news.
If the file is required for the rest of the script to function properly, require it.
Per http://www.alt-php-faq.org/local/78/:
Unlike include(), require() will always read in the target file, even if the line it's on never executes. If you want to conditionally include a file, use include(). The conditional statement won't affect the require(). However, if the line on which the require() occurs is not executed, neither will any of the code in the target file be executed.
In simple language if we use require we must sure that the file is existing in that era while it is not necessary in case of include. But try to make sure file exist.
Include and require are identical, except upon failure:
require will produce a fatal error (E_COMPILE_ERROR) and stop the script
include will only produce a warning (E_WARNING) and the script will continue
You can understand with examle
include("test.php");
echo "\nThis line will be print";
Output :Warning: include(test.php): failed to open stream: No such file or directory in /var/www/........
This line will be print
require("test.php");
echo "\nThis line will be print";
Warning: require(test.php): failed to open stream: No such file or directory in /var/www/....
Require() and include() are the same with respect to handling
failures. However, require() results in a fatal error and does not
allow the processing of the page. i.e. include will allow the script
to continue.
Related
I have 3 different files-
fileMainIncludeEverywhere.php
...
include_once('fileMinorInclude.php');
?>
fileMinorInclude.php
...
include_once('fileMainIncludeEverywhere.php');
...
fileToRun.php
...
include_once('fileMainIncludeEverywhere.php');
...
I have a lot of files like fileToRun.php.
Currently I'm not facing any errors in my code, but I want to know if there's any case where this would fail?
I think no error in this case. Because include_once will only load the file for the first time then upcoming load request will be rejected for the same file.
So from your example:
fileToRun.php will load fileMainIncludeEverywhere.php (first call)
fileMainIncludeEverywhere.php will load fileMinorInclude.php (first call)
fileMinorInclude.php will call to load fileMainIncludeEverywhere.php but it will be rejected as it has been already loaded in first step.
Hope it will help.
include_once:
The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again, and include_once returns TRUE. As the name suggests, the file will be included just once.
Here "code from a file" also entails the executed PHP file.
Note it's generally best practice to use require_once() instead of include_once() unless you've got a specific reason for using include_once() (like say including optional template components). This because require_once() will terminate (fail fast) if the required resource is not found, and not finding it normally should be a terminal failure.
I am calling similar PHP scripts from different locations in WordPress.
They all have in common that they call another php file (genlib.php) which its some kind of library with a large number of php functions.
When I ran into the "cannot re-declare function ... in genlib.php" error, I wrapped each function into an "if !function_exists" condition to avoid this.
This is ugly because I have to do it so many times.
How can I avoid this on the level where I include the genlib.php file in my scripts?
I believe using include_once or require_once in all files that include the file genlib.php should solve this problem.
Update: Based on the OP's comment, it appears that this solution does not work for multiple different scripts loading libraries which include_once genlib.php. In this case, the OP may have to regress to using a guard statement wrapping the entire genlib.php.
if (!defined('GEN_LIB_PHP')) {
define('GEN_LIB_PHP', true);
// Rest of code for genlib.php
}
Use include_once() for the file. This prevents the system from running the code again, if the file was included before. The same applies for requrie_once().
Is it a good idea to use some 'my_require_once' function instead of standard require_once to check if the required file exists and handle the case if not (for example, display some special error page instead of FATAL_Error message displaying the structure of your application (path, filenames etc.) or is it just useless? If second, then, what is a better practice to include files?
Update:
I dont want to disable all error messages, though, while I'm not very experienced in PHP and I'm afraid it can hide some bugs from me for quite a long time.
Thanks
I think the difference between the require_once() and include_once() functions is that the require_once() causes PHP to deliver a fatal error and script execution stops. So if you want to keep executing then use include_once() and simply use it in an if statement to see if your file was included and then handle the errors as necessary.
EDIT
If you would like to suppress an error message in PHP you can use the # symbol.
if(!#include_once("somefile.txt")) {
print("File could not be found...");
}
Among include, include_once, require and require_once I always just use require_once. Many third-party frameworks just use require_once as well.
Can anybody please describe a real scenario that another construct must be used?
IMHO there is no real scenario that fits include and include_once because of two reasons:
It's highly unlikely that your intention is to include a file and at the same time you don't really care if it's included (e.g. if the file does not exist and execution continues).
Even if that is the case, include will emit a warning which is bad style (zero-warning code is a good thing to strive for). You can prevent this most of the time with a check like is_file, but then you know that the file does exist so why not require it?
For require vs require_once: if a file can legitimately be parsed more than once (e.g. an HTML template) use the former. If it brings code inside your application (the vast majority of cases) use the latter.
The require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.
The require() function is identical to include(), except that it handles errors differently. If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.
The only difference between the include/require and include_once/require_once statements is how many times a given file will actually be loaded. When the include_once/require_once statements are used, the file cannot be loaded or executed multiple times. If an attempt is made to load a file twice using one of these two methods, it will be ignored. Because it is unacceptable to define the same function multiple times within a script, these functions allow the developer to include a script as needed without having to check whether it has been previously loaded.
<?php
include ('library.inc');
$leap = is_leapyear(2003);
require ('library.inc');
$leap = is_leapyear(2003);
?>
If both statements will allow the current script to execute the code in a separate file, what is the difference between the two?
There are two major differences:
the first is the capability to return values and the second is under what circumstances the requested file is loaded. When an include statement is used, PHP delays the actual loading of the requested file until the script reaches the point of executing the include statement and replaces the include statement with the contents of the file. Conversely, in the case of the require statement, the require statement is replaced with the contents of the requested file regardless of whether the require statement (and thus the contents of the file) would have executed in the normal progression of the script.
Quoting above paragraph from http://82.157.70.109/mirrorbooks/php5/067232511X/ch01lev1sec8.html
NOTE
The capability to return values from external files is limited only to the include and include_once statements. The require and require_once statements cannot be used in this fashion.
require give Fatal error but include give Warning
The include construct will emit a warning if it cannot find a file; this is different behavior from require, which will emit a fatal E_COMPILE_ERROR level error.
The same difference applies also for include_once and require_once.
When use include and when use require, is described very good in answers to Difference between require, include and require_once?
From the my point of view, there are 2 things.
if you have something, which is absolutely required to be present in your application, you should use require/require_once to include such definitions. That way you'll get fatal errors instead of warnings and during development that will simplify finding problematic code.
if you're including external resource or something which may be missing, it should be included with include/include_once in order to be able to suppress possible include errors using # operator.
I received the following error:
[27-Apr-2009 10:26:06] PHP Fatal error: Cannot redeclare alphanumeric() (previously declared in /home/iddoc/public_html/lib/common.php:6) in /home/iddoc/public_html/lib/common.php on line 8
Notice this:
/home/iddoc/public_html/lib/common.php:6) in
/home/iddoc/public_html/lib/common.php on line 8
Here are the offending lines:
function alphanumeric($str) {
return strtolower(preg_replace("/[^A-Za-z0-9]/",'',$str));
}
Prior to these lines there are only comments. There is no other declaration of that function anywhere else in that file or any other.
Strange, no?
Are you using require_once() to include common.php everywhere? If you use just require or include, that will cause this issue.
Are you using require/include to reference the file? This is a common error when including a file twice. PHP doesn't know what to do if it sees two declarations, even if they're from an identical file.
Try using this:
include_once('lib/common.php');
It seems like you may have included the common.php file more than once. The second time it loaded would cause errors like that since the function is already loaded.
It is an odd error, but will probably seem logical once the problem is figured out. I would suggest looking at your includes, or switch them to include_once. Maybe see what debug_print_backtrace() outputs before that function loads.
Sounds like you've got the common.php file included more than once. Do you use include(), require() or require_once() for your includes?
is this common.php included earlier? That could cause this error.
You should always use include_once or require_once when including code files in PHP. There are exceptions to this rule but if you aren't sure, use the _once versions. The only time it is okay to use include or require is when you know the file will never, ever be included again in the same program OR the file being included does not declare functions (without protecting them with an if (function_exists()) {} block).
As an example, templating system are one of the very few uses where you probably don't want the _once version.
Check for recursive includes and make sure your blocks are not executed several times.