Difference between "include" and "require" in php - php

Is there any difference between them? Is using them a matter of preference? Does using one over the other produce any advantages? Which is better for security?

require will throw a PHP Fatal Error if the file cannot be loaded. (Execution stops)
include produces a Warning if the file cannot be loaded. (Execution continues)
Here is a nice illustration of include and require difference:
From: Difference require vs. include php (by Robert; Nov 2012)

You find the differences explained in the detailed PHP manual on the page of require:
require is identical to include except upon failure it will also produce a fatal E_COMPILE_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.
See #efritz's answer for an example

Use include if you don't mind your script continuing without loading the file (in case it doesn't exist etc) and you can (although you shouldn't) live with a Warning error message being displayed.
Using require means your script will halt if it can't load the specified file, and throw a Fatal error.

The difference between include() and require() arises when the file being included cannot be found: include() will release a warning (E_WARNING) and the script will continue, whereas require() will release a fatal error (E_COMPILE_ERROR) and terminate the script. If the file being included is critical to the rest of the script running correctly then you need to use require().
For more details : Difference between Include and Require in PHP

As others pointed out, the only difference is that require throws a fatal error, and include - a catchable warning. As for which one to use, my advice is to stick to include. Why? because you can catch a warning and produce a meaningful feedback to end users. Consider
// Example 1.
// users see a standard php error message or a blank screen
// depending on your display_errors setting
require 'not_there';
// Example 2.
// users see a meaningful error message
try {
include 'not_there';
} catch(Exception $e) {
echo "something strange happened!";
}
NB: for example 2 to work you need to install an errors-to-exceptions handler, as described here http://www.php.net/manual/en/class.errorexception.php
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");

<?PHP
echo "Firstline";
include('classes/connection.php');
echo "I will run if include but not on Require";
?>
A very simple Practical example with code.
The first echo will be displayed. No matter you use include or require because its runs before include or required.
To check the result, In second line of a code intentionally provide the wrong path to the file or make error in file name. Thus the second echo to be displayed or not will be totally dependent on whether you use require or include.
If you use require the second echo will not execute but if you use include not matter what error comes you will see the result of second echo too.

In case of Include Program will not terminate and display warning on browser,On the other hand Require program will terminate and display fatal error in case of file not found.

Related

How to automatically stop any script and redirect to an error page if an error/warning/notice is uncaught

EDIT: about the linked answer above, it's similar but different, since my goal is to debug the error in the error page.
Sometimes an unexpected error is hard to debug, since the error report is printed inside strange HTML elements, like an hidden div or a option element.
Is there not a way to automatically store error objects in a global variable and redirect the script to an error page, if any uncaught error is fired? And is there a way to do this for all errors, included the ones that normally doesn't quit the script, like warnings and notices?
You do this with a custom error handler. Turning errors into exceptions is a good way and allows you very fine grained control over error handling:
set_error_handler(function ($errno, $errstr, $errfile, $errline) {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
});
You may decide for which errors to throw exceptions and which to ignore; for example you may want to ignore or just log E_NOTICEs. With a global try..catch block or a custom exception handler you can now very easily decide what to do in case of errors.
Indeed there are ways to both redirect errors to pages, log them, track them, and what not. PHP is quite flexible. The good news is you don't have to homecook such methods, frameworks are available for that, but you can also survive without these as built in error handling facilities of PHP are sufficiently usable. If configured properly, PHP will abort on errors (or warnings, you decide), log them, and even return HTTP 500 Server Error code if plugged into a web server.
You may need to configure PHP properly. It is perfectly capable of a better error handling workflow. First of all, disable error printing, this is not how well behaved applications should report errors, and at worst, helps malicious users to break their way into your systems, using printed error output. You are not the only one viewing your webpages, you know, and not all users get confused seeing these, some wait for these. This is one of the directives you can use, editing the "php.ini" file, which configures PHP; it disables mixing error output with whatever else PHP outputs as part of content generation:
display_errors = "0"
You can also set it to "stderr", which is a good thing to do when debugging scripts using command line PHP invocation, as the output will be sent to another file channel, the so called standard error.
Take now heed of the following "php.ini" directive:
log_errors = "1"
The above will have PHP log errors either to a file or using web servers error logging facilities, depending on how PHP is invoked. On UNiX systems, the log file, listing the error and its details, will reside in "/var/log/www/", for instance.
Take a good read through the PHP documentation on error handling and reporting, starting perhaps at the following page:
http://www.php.net/manual/en/book.errorfunc.php
Don't forget to read on installation configuration. And I repeat again, NEVER have PHP display errors for a public PHP script! (and yes, I am aware that you are debugging, but I can't stress this point enough these days).
Thanks to #MladenB. and deceze, I solved my problem. This is how I coded the solution:
in a config.php file, to be included in your scripts (it's better to move the functions to a personal library file):
<?php
function my_error_handler($errno, $errstr, $errfile, $errline)
{
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
function my_exception_handler($e)
{
/**
* Exception handler that pass the error object to an error page.
* This is to avoid bad displaying or hiding of error reports.
*
* #param $e Exception The exception to manage
*/
if (session_status() !== PHP_SESSION_ACTIVE)
{
session_start();
}
session_register_shutdown();
$_SESSION['error'] = $e;
header('Location: error.php');
exit();
}
set_error_handler('my_error_handler');
set_exception_handler('my_exception_handler');
in error.php:
<?php
session_start();
session_register_shutdown();
$e = $_SESSION['error'];
echo '<h2>Stack trace</h2>';
echo var_dump($e->getTrace());
throw $e;

importing files in php using require() not working

i tried the following code to import two files
<?php echo "php";
require('../globalvasr.php') or die("error");
require('../newcosn.php') or die("error2");
$config = new GlobalConfigs();
?>
It does not shows error and it just simply displays a blank page.Also i am unable to use the variable defined in those two files.
Like $config->DBNAME.
I dont know whats wrong in this.
Please help me find it.
Thank you.
require, in contrast to include, automatically dies and does not have a return value.
This means the or die() is bad. Better:
<?php echo "php";
require('./globalvasr.php');
require('./newcosn.php');
$config = new GlobalConfigs();
?>
Require generates a fatal error when require fails, causing the script execution to stop immediatly.
As you seem to be running in a web env, your output (all echo or print statements) is buffered until the end of the script.
So here the require fails, causing a fatal error (that should be available in the error log) before the output buffer is emptied, preventing your first "echo" to be sent to the browser. that's why you get a blank page.
Try replacing the require with an include, you will get a warning instead of the fatal error.
if you have blank page, set error_reporting: E_ALL and Display_errors: On in php.ini or put on start of your script these lines
error_reporting(E_ALL);
ini_set('Display_errors','On');
then you will see errors

PHP require fails with no error

Here is the code I have been struggling for several hours:
if ((require $_SESSION['ROOT_PATH'] . '/templates/core/menu_js.php') == 'OK') {
echo 'OK';
} else {
echo 'KO';
}
If I understand the PHP documentation on the "require" directive correctly, the "KO" should never be written because, if the require doesn't work, an error is raised.
In my case, the "KO" is always displayed even with error tunning :
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR);
Note that the same require (or include) works perfectly in other pages of the site.
EDIT
The if structure has been added after watching the documentation.
At first, I had a single line :
require $_SESSION['ROOT_PATH'] . '/templates/core/menu_js.php';
As I checked that this line was not working, I added the if.
By the way. Required page (when it works) adds a script tag to calling page that I never see on this unique page. On any other page where this require is used, the script appears on output.
So my question should be "if the output of the required php file is not displayed, why is there no error raised ?"
According to the documentation
Successful includes, unless overridden by the included file, return 1... Also, it's possible to return values from included files. You can take the value of the include call as you would for a normal function.
So your file isn't returning 'OK'. It's returning either 1 (for success) or a custom value.
require is a language construct, not a standard function. By using require you're already indicating the code should fail if the file isn't found. Most likely you do not need to check the return value.
This only works the way you expect if menu_js.php contains return 'OK';. Otherwise the require works just fine, but the returned value is not "OK", which is why your "KO" condition is triggered. require doesn't return 'OK'. If the require does not work, the program is halted immediately, your false condition will never be hit the way you think it will.
There are some mistakes here:
According to the PHP documentation:
require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error.
A fatal error will stop your script execution.
require returns what the included file returns:
// a.php
return 'test';
// b.php
$result = require 'a.php';
echo $result; // will display 'test'
So, don't test the return value of require! Use is_file(), then if true, require that file!
You cannot use require in if
Use this
if(file_exists($_SESSION['ROOT_PATH'] . '/templates/core/menu_js.php'))
{
echo 'OK';
} else {
echo 'KO';
}
While it's true that the require will not return anything, making the conditional always return 'KO' since the left hand value in the parenthesis will never equal 'OK', you can check to see if the file has failed by setting the display_errors ini value in this script temporarily On.
Since you have your error reporting set to catch this, your display_errors is probably off, therefore not showing you this. Set it for this script like this:
ini_set('display_errors', 'on');

PHP: require versus include: practical considerations?

I've read that one of the differences between include and require is that
while include only includes the included file if the include statement is
encountered, require includes the file into the file hosting the require
statement even when the require code is not reached by the execution flow.
How can this have any implications. After all, if I have a file which says:
<?php
echo __LINE__;
?>
the output will always be 3, instead of printing the line inside at the
position inside the file which includes such include file.
This is simply not true, as far as I know. If the require line is not reached in the code, the file will certainly not be included.
The PHP Manual on require states:
require is identical to include except upon failure it will also
produce a fatal E_COMPILE_ERROR level error.
(emphasis on "except" added by me)
As far as I know, that's not how require works. The only practical difference is that require will cause your script to terminate if the file cannot be included, and include will just throw a warning and keep executing.
A very important idiom depends on your stated behavior not being true: conditional required files.
if(is_secure_page()) {
require "security.php";
}
Both require and include include their files at the point where they are reached in the execution flow.
A simple test case for this is:
if (false) {
require_once("Nonexistent.php");
}
echo "I'm doing SCIENCE and I'm still alive.\n";
Let's say you are running a mission critical application and will lose $1 per second. And some libraries are only used in certain case and are not affecting your business flow. You should probably use include_once for these optional libraries. Because if the file is not there require will stop your application from running with a fatal error.
require, or even better, require_once should be used exclusively when you want to include code that is actually required by the application, e.g. any libraries you need. include and its brother, include_once should only be used when the included file is not necessary to the execution of your script, such as when you are loading a sidebar or some tangental content.
The only real difference between the two statements is that is the file is not found, require with throw a fatal error, and include will just throw a warning and go on happily chugging away.
I believe that both require and include are loaded and parsed in exactly the same manner. If require would load a file in a given context, so would include.
I personally always use require_once, I find in most cases it's what you need (either you get the page once or you halt the script). And include throws warnings that you need to hide if you want to "try" including stuff. But that's just bad programming practice, a simple if (file_exists($file)) require_once $file; does the trick and totally beats include.
So in my opinion, require wins by far.
PS: Beaten by a sec !

include or required

What should I use in the following statement? Include or required.
if(a ==b){
require 'requiredfile.php';
} else {
require 'requiredfile_2.php'
}
If in a function, I know that one, either include or require, only includes the file when called, the other one will include the file regardless. Am I correct?
The difference between include and require is that include will only emit a warning when the file is not found, and require will terminate with a fatal error.
If you are loading vital program parts, you probably want to go with require.
Manual
require() is identical to include() except upon failure it will also 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.

Categories