how to include a php file that already includes another file? - php

I am trying to include 2 php file in two separate <td> tags in the same table.
<td><?php include 'login.php';?> </td>
<td><?php include 'register.php';?> </td>
Both the php files include another php file for connecting to a database (eg. <?php include 'database.php';?>
Now, the problem is, the second file doesn't show up in the table. First file works.
Php files work independently. No problem with the code.
I removed the include in 1.php and everything worked fine - ie. both the files show up in table.
My conclusion is, it goes on including indefinitely. Now, how do I solve this?
regards
Ganesh Kumar

You can use 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.
As the name suggests, it will be included just once.
i.e.:
include_once('database.php');
include_once('login.php');
include_once('register.php');

You actually have several options, now that I think about it.
Require_once:
require_once('database.php')
This is the most accepted method for files such as this one that you describe, as it will hard-fail if the file cannot be included. For files that do program instantiation (I.e. database connection) this method is preferred.
Include_once:
include_once('login.php')
I've never found a reason to use this statement over require_once; however, that said, it doesn't mean there isn't one. If you have a file that does some instantiation of something related to your programme that isn't mission-critical, then you could suppose to use this directive over the other.
Define Include Constants:
This method requires a bit more explanation: instead of starting your included file (database.php in our example) off with the code for it, start it off in a manner similar to C/C99/C++.
<?php
if (!defined("INCLUDED_DATABASE"))
{
define("INCLUDED_DATABASE", true);
// add main body of file here
}
?>
This method basically accomplishes the same thing as the include_once and require_once, except that in no circumstances will it ever actually process the body twice in one request, even if you forget to use _once as a suffice to your include/require method. This goes back to the old days of C/C99/C++
where including a file twice would hard-fail the compiler, as duplicate definitions would take place.
Personally, I have always preferred the last option: it's the most strict. Yes, require_once and include_once when used diligently will have the same effect, but suppose someone (not even you necessarily) is modifying the application and accidentally does an include or require without the _once suffix, they will be having a bad day. This method prevents that.
That said, I still use a require_once when necessary, and a require if it can be included multiple times. (Files with that designation are not designed with the define construct.)

Related

How are include_once loops handled in php?

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.

Bypass for cannot re-declare function

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().

A practical scenario for using include(), include_once() and require() constructs

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.

Using require_once inside a method

From what I understand using something like require_once will essentially copy and paste the code from one file into another, as if it was in the first file originally.
Meaning if I was to do something like this it would be valid
foo.php
<?php
require_once("bar.php");
?>
bar.php
<?php
print "Hello World!"
?>
running php foo.php will just output "Hello World!"
Now my question is, if I include require_once inside a method, will the file that is included be loaded when the script is loaded, or only when the method is called?.
And if it is only when the method is called, is there any benefit performance wise. Or would it be the same as if I had kept all the code into one big file.
I'm mainly asking as I've created an API file, which handles a large amount of calls, and I wan't to simplify the file. (I know I can do this just be creating separate classes, but I thought this would be good to know)
(Sorry if this has already been asked, I wasn't sure what to search for)
It will only include when the method is called, but have you looked at autoloading?
1) Only when the method is called.
2) I would imagine there's an intangible benefit to loading on the fly so the PHP interpreter doesn't have to parse extra code if it's not being used.
I usually use the include('bar.php'); i use it for when i use databvase information, i have a file called database.php with login info and when the file loads it calls it right up. I don't need to call up the function. It may not be the most effective and efficient but it works for me. You can also use include_once... include basically does what you want it to, it copies the code essencially..
As others have mentioned, yes, it's included just-in-time.
However, watch out for variable definitions (require()ing from a method will only allow access to local variables in that method's scope).
Keep in mind you can also return values (i.e. strings) from the included file, as well as buffer output with ob_start() etc.

Are there any downsides from using Include() or nested include's()?

I am not an expert in PHP. I am trying to increase the use of include() to make my website code as clean as possible instead of just copying, for example, code of the header in all the pages. I have two questions
1 . Is it good practice to use include() a lot in terms of server requests, speed, ...etc ?
index.php
(bunch of code)
<? include("connect.php") ?>;
(bunch of code)
<? include("header.php") ?>;
(bunch of code)
<? include("footer.php") ?>;
2 . Is it fine also to use nested include's()? example:
header.php
(some code)
<? include("searchFormInput.php") ?>;
now index.php will include header.php, then header.php will include searchFormInput.php as well
is this fine?
Thanks a lot
Yes, including is a common practice.
Yes, including gives you slight performance penalty (very small).
But including gives you readibility gain and thanks to it will be easier to employ DRY rule. Just remember the following:
if the file contains some code that should be executed only once (some setup, class definitions, function definitions etc.), use include_once() (it will have no effect if invoked again on the same filename),
if the file contains some code executed multiple times (eg. some template for a form), use simple include(),
if something is required for your application to work (eg. some security code, some setup etc.), use require() instead of include() or require_once() instead of include_once() - if the file will not be found, PHP will throw fatal error and will stop executing your script,
The principle downside to nesting includes is that you are likely to run into situations when cross-dependencies cause a file to be include more than once. That is easily solved by the use of include_once(), though.
In your example however, with header.php including searchFormInput.php, you probably won't have problems assuming these files both mostly produce HTML output rather than parsing classes and dependencies.
On the other hand, if you had some structure like
connect.php includes config.php
session.php includes config.php
you would need to use include_once('config.php').
include,require will read file and excute codes inside it.
i made some tests on speed of include and file_get_contents
results was include and require is slow in compare
so my advice don't increase numbers of inclusion.
I think you should look at autoload with PHP once. You should not need to care the include of every and each file. Just adjust your autoload and that will take care of all these. You needs to do object oriented programming with this.
It's fine to that in terms of performance and it keeps your code clean and reusable to a certain extent. However, I recommend that you use templates for this kind of code inclusion, where you load all your information into variables and then call them in your template. Consider a template engine http://www.smarty.net/ or maybe a PHP framework or CMS http://drupal.org/ which should make your life easier in the short and long run!

Categories