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...");
}
Related
According to php.net:
The include construct will emit a warning if it cannot find a file;
this is different behavior from require, which will emit a fatal
error.
However, there's nothing more about possible errors or error handling.
Does it mean that the only reason why include or require may fail is not being able to find the file? There might be any other reasons?
I also found this & this questions about fail handling.
So, considering I want to include another .php file stored on my server following best practices, and I write:
if ( file_exists('myFile.php') ) {
require_once 'myFile.php';
}
Can I consider this script to be completely "safe"? Will myFile.php always be included if it exists?
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.
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'm writing a PHP application for the first time (other than toys and exercises), and I'm at a loss to understand why PHP includes both an include and a require construct.
Before you write an answer explaining the differences between the two, let me first say that I do understand the difference - include produces a warning and keeps on going, and require produces a fatal error. My question is: when would you want to include, but not require a file?
Maybe it's a failure of imagination on my part, but there don't seem to be any files in my application that I don't want to scream about if they're not there. Oddly, this doesn't make me want to use require since it seems impossible to properly handle a failed require, so instead I use a helper function along the lines of this (warning: air code):
public static function include($filename) {
if (is_readable($filename)) {
if (!#include($filename)) {
throw new FileNotFoundException("File deleted after readable check");
}
} else {
throw new FileNotFoundException("File missing or unreadable");
}
}
I guess what I'm asking is:
What sorts of files would you really want to optionally include in an application?
Whether or not you want a file to be required or optional, why wouldn't you just handle that in a function like a modified version of the code I wrote above?
I'd use require for loading files essential for the app itself, i.e. require 'database_config.php', require 'core.php'. If this fails, you want it to fail as fast, hard and merciless as possible, since something is obviously wrong with your app installation. In this state it's not even guaranteed that it could handle a thrown exception properly, and require produces a very clear error message without any extra code.
include should be used for things like template files that you want to use when the app is already up and running and can handle its own errors gracefully.
Example:
include 'error_handler.php';
set_error_handler('error_handler');
/* something bad happens */
Warning: 'error_handler.php' not found!
Error: Specified error handler "error_handler" doesn't exist.
At some point you simply rely on basic files, even if it's just your error handler. You'd have to introduce extra code to handle a missing error handler gracefully, and even then the best you could do is output some error and die (unless you want to get into the game of catching errors gracefully even if your error handler doesn't exist). It's best to simply require 'error_handler.php'; you can include and custom handle everything after this if you want to.
What sorts of files would you really
want to optionally include in an
application?
I normally use include with static HTML blocks (header, footer, menu, search box, survey form...) and require with PHP functions or classes. It's unlikely that the footer block will disappear but, well, I suppose it's a nice visual clue when I look at the code.
Whether or not you want a file to be
required or optional, why wouldn't you
just handle that in a function like a
modified version of the code I wrote
above?
The # operator is said to be expensive and, anyway, I think that including an external file is a basic operation that should be covered by basic language. Your code also adds a new dependency: if you store it in a required block your optional blocks will no longer be 100% optional ;-)
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.