How to include files with die(); function? - php

file1.php and file2.php with die(); function.
include.php:
<? include 'file1.php';
include 'file2.php' ?>
file1.php
<? echo 'included'; die(); ?>
file2.php
<? echo 'not included'; die(); ?>
How can I include both files with die(); function?

Non-English Speakers:
You can provide your question in your native language as well, and somebody here may be able to translate it for you. Just make your best effort to ask in English, and add your native tongue below.
If you would like to test whether the includes happened successfully, you can test the return value of the include function itself:
// http://us3.php.net/manual/en/function.include.php Example #4
if ((include 'file1.php') != 'OK') {
die();
}
You may also consider require() instead of include() depending on your needs:
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.

If I understand correctly what you are trying to do then unfortunately it isn't possible.
die(); will stop the script from executing at the point from where it is called.

Here is how to include a file, or die with a message if the include fails code sample.
(include('file.php')) || die('Failed to include file!');

if (!condition){
include_once('./inc/header.inc.php');
echo "Errormessage";
include_once('./inc/footer.inc.php');
die();
}
I hope this is what you wanted.

Just a minor improvement to LorenzoP's method:
(#include("file.php")) or die("Failed to include!");
// notice the # sign!
This way, you save yourself 2 ugly lines of php warning when inclusion fails. Otherwise I think this is truly the best way to handle failed includes. (Also, his answer should be the accepted one.)

If the execution of your included file is not dependent on the current file (no shared variables, functions, etc.), then use
file_get_contents('link_to_file.php');
instead of an include method. When you force the file to execute independently it will not make a effect in the script execution.

die() is just an exit with an error, you can't include files with it and I don't really understand why you want to. Could you provide more details as to what you're trying to accomplish?

Related

Connection Error in PHP

Ohk, I just started to learn PHP and MySQL. Everything was going fine untill this thing boiled up my mind.
Here is the problem.
I have two php files in the same directory.
mysql.php--->
<?php
require("connect.php")or die(mysql_error());
?>
connect.php--->
<?php
error_reporting(0);
$connect=mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("phpacademy")or die(mysql_error());
echo"Connected!";
?>
The problem is that whenever I am running the connect.php script directly, its working fine.
But when I run mysql.php to connect to the other script it gives the following error:
Warning: require(1): failed to open stream: No such file or directory in C:\xampp\htdocs\stckovrflw1\mysql.php on line 3
Fatal error: require(): Failed opening required '1' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\stckovrflw1\mysql.php on line 3
Its not getting the file even though it exists and the spelling is obviously not incorrect.
And the most amazing part is that, as soon as I remove the or die() everything works like a charm.
As I am a beginner I have no idea whats going on. I supposed that or die() is just for developer's or user's help to see the exact error, but in this case it is causing the error itself.
Do help!!!
Thanks in advance...:)
P.S.: I am running on localhost as mentioned in code also.
or has a higher precedence than require/require_once. Therefore php evaluates
('connect.php') or die("blah blah")
before passing the result to require. Or takes two boolean operands. ('connect.php') evaluates to true therefore the whole expression is true and
require true;
is invoked.
require takes string as parameter, so true casts to 1 by php.
so it became require 1 in your case
that generate failed to open error
A bug reported on bugs.php.net https://bugs.php.net/bug.php?id=15438 says:
"Because include() is a special language costruct, parentheses are not
needed around its argument. Take care when comparing return value.
<?php
// won't work, evaluated as include(('vars.php') == 'OK'), i.e. include('')
if (include('vars.php') == 'OK') {
echo 'OK';
}
// works
if ((include 'vars.php') == 'OK') {
echo 'OK';
}
It is mysql_select_db and not mysql_selectdb
and by the way if you have begun learning php and mysql, better get yourself trained using mysqli and not mysql
You don't have to use die() in the require line, if the file is not present PHP will automatically throw error
FYI:
die() method comes in handy for debugging yes!! thts true when you want to stop the execution of some loop or code flow when you want to analyse what are the variables that you get as output and the ones that you dont
<?php
require("connect.php")or die(mysql_error());
?>
Does not work. PHP at first evaluates the expression
("connect.php") or die(mysql_error())
And this expression is always true. The result ist:
require true
This doesn't work. You even don't need to check the connection because you checked this in your connect.php. But double checking is not wrong and it's better for future compatibility (for example you can change your implementation and remove the check in connect.php). So you can use this instead:
<?php
require("connect.php");
if(!$connect)
die(mysql_error());
?>
error_reporting(0);
$connect=mysql_connect("localhost","root","") or die(mysql_error());
mysql_selectdb("phpacademy",$connect)or die(mysql_error());
echo"Connected!";
You need to set you PHP.INI
It is clear that your include path is set to default, which is (include_path='.;C:\xampp\php\PEAR')
You PHP-config is looking for file in 'C:\xampp\php\PEAR', which is not there.
Try set_include_path() (reference: www.php.net/set_include_path)
<?php
set_include_path('C:\xampp\htdocs\stckovrflw1\');
require("connect.php")or die(mysql_error());
?>
mysql_selectdb("phpacademy",$connect)or die(mysql_error());

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 !

PHP include practices

Does anyone here know when PHP executes include and include_once calls?
I'm wondering because I come from a Flash and Desktop development background where you have to import your classes at the beginning of each class.
But now that I am starting to build more complex PHP code, it seems like it would be better to just include classes when I actually need them to save on loading time. For example, look at the following psuedo code:
if (I_need_to_check_login)
{
include_once "Class.class.php";
$C = new Class();
}
If I do this, is the file Class.class.php going to be included everytime the code is run or only when I execute the include_once.
I'm a bit of a Class freak and usually build a class for just about any functionality used by my apps, so I often have lots of class files.
include, include_once are standard PHP instructions. This means the interpreter executes each include, include_once when he finds one in the flow of the program. If a control structure avoids to execute a piece of code which has an include instruction, this one won't be executed.
In your example, the include_once, will be executed if, and only if, I_need_to_check_login is true.
Includes are only performed if interpreter ever gets there. eg:
$variable = false;
if ($variable) {
include 'a.php';
} else {
include 'b.php';
}
In this case only b.php would be included.
For more on its behavior: PHP Manual - include
Yes, every time you have to call: $C = new Class(); you will have to require or include the file. Now what you can do instead of include_once is:
if (!class_exists('MyClass')) {
include("Class.class.php");
}
which mean you might not have you include it again, if you already included it before. This will also improve performance since include is faster to execute than include_once.
Files are actually included only if you perform include_once command.
So if that I_need_to_check_login evaluates to false - file will not be included at all
It can be easily checked by yourself with adding echo "I've been included"; exit; to the first line of that file.

Difference between "include" and "require" in 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.

Should require_once "some file.php" ; appear anywhere but the top of the file?

Is the following example appropriate for PHP's require_once construct?
function foo( $param )
{
require_once "my_file.php" ;
//
// do something here
}
Or is it more appropriate to only have require_once constructs at the beginning of the file?
Even though the file being included is useful only in the context of the function, is it not better to have includes at the top for readability and maintainability?
It comes down to a matter of coding style and opinion. Personally I keep all my require_once statements at the very top of my files so I can easily see which files are included where, nothing worse then some buried include messing with your scripts. However, if you have several large required scripts that are only required for certain functions, then putting the require_once inside a function would be OK from a performance stand-point, just make sure to put a note at the top of the page.
<?php
//require_once "my_file.php" (see function foo)
function foo($param) {
require_once "my_file.php";
}
This is something of a religious debate.
PROS for require and include statements at the top of the file:
dependencies are clearly documented in a consistent reliable place.
increased readability/maintainability
OP code caching is simpler (although you could argue that this doesn't affect the developer directly)
CONS for require and include statements at the top of the file:
If you're doing some kind of dynamic runtime including (such as with __autoload()), a hardcoded statement at the top of the file is impossible.
If only one execution path in the code uses an include, having it included every time, unconditionally is a waste of resources.
long list of include or require statement is just noise the developer must scroll past when editing a file. Of course, a long list of dependencies can be viewed as a sign that the code should be broken up into smaller more focused pieces, so maybe you could spin this one as a PRO because it makes a code smell stand out.
If you don't want to load a file unless it's needed, look into autoloading - on newer PHP via spl_autoload_register().
Maybe you only need the included file in certain cases, and you'd like to avoid including it if you don't need it at all, if it's a big file. So, I guess you could go for a require_once only in one branch of an if - else statement.
When using require_once keep in mind that this is not some pre-processor directive. The require_once statements are executed when PHP runs the code and it only executes if the specific script has not already been included during the execution.
For example:
conf.php:
<?php
$maxAge = 40;
?>
myscript.php
<?php
function foo($age) {
require_once("conf.php");
if($age > $maxAge)
return "1";
else
return "0";
}
echo foo(30); // Echos 1
echo foo(30); // Echos 0
?>
The require_once is not executed on the second call to foo(..) since conf.php has already been included once.

Categories