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

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!

Related

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

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

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

How do I rewrite PHP code blocks before they are passed to the interpreter?

What I am trying to do is write a parser for PHP that interprets whitespace instead of brackets. I can do rewriting bit and output PHP, but what I'm not sure is how best to integrate this into an application.
In an ideal world, I imagine the best thing would be to put an include at the top of the file, which in turn rewrote all the code blocks that follow it into proper PHP syntax as they are passed to the interpreter, but I am not aware that blocks of code can be passed in this way.
Another alternative is to write it as a server extension, but I would prefer not to do this, as it makes it less accessible.
Is there an easy way to architect this?
There is a way to do this with Stream Wrappers.
With that you can basically read and re-write any code that is read by PHP before it is actually interpretted. with fopen(), fwrite(), include, require, file_get_contents() etc.
So in your case you could listen for any file that is require(_once) or include(_once) and do with the code you like. You will get the entire code in a variable and with that you can simply do all sorts of replacements in strings with regex and what not.
The only downside is, is that your index.php can't make use of this method since it is not catched by any include or require. But any other code file that is included from there can be catched by the stream wrapper.
Here is an article about a plugin system that uses that method. Maybe it can be of any help.
http://phpmyweb.net/2012/04/26/write-an-awesome-plugin-system-in-php/
In there you'll also find a link to a guthub page with the source of the plugin code. In there you can basically see how to setup your Stream Wrapper class. From there on you can make up your own code as you do not have to intercept any method calls etc. like the plugin is doing.
I don't think your include idea would work as described. Since the code would be missing braces, it probably would not make it through the normal PHP parser without throwing a 500 error. So the file you want to include could never do its work.
The opposite approach might work. Write a parser script and have it read and execute your "whitespace" PHP files.
URLs might look like this: mydomain.com/my-parsing-script.php?file=script/to/parse.php
Then you'd edit .htaccess to rewrite all your URLs to make that stuff invisible to the user.
The parsing script would simply open the "whitespace" file and do some regex magic before passing the script to eval();

Custom stream wrapper with include or eval?

Overview
I'm currently writing a template engine. It even supports multiple "format"s. Currently it can parse .php files and .tpl (specific to this engine).
I'll give you a little example of both, just to give you an Idea.
template.php:
Name: <?php echo $this->h($name) ?>
Posts:
<?php foreach($posts as $post): ?>
- <?php echo $this->h($post->name) ?> (<?php echo count($post->comments) ?> comments)
<?php echo $this->render('post/shortpost', array('post' => $post)) ?>
<?php endforeach ?>
This is basicly just a standard PHP.
template.tpl
Name: {>$name}
Posts:
{foreach($posts as $post):}
- {>$post->name} ({=count($post->comments)} comments)
{=:render('post/shortpost', array('post' => $post))}
{endforeach}
This templating "language" simply gets translated into PHP above.
Comparission
eval()
Currently these template's are parsed using eval().
Pro
I don't have to change any code
Contra
when an error occurs in a template you only get a useless error message which doesn't
tell you in which file the error occurs and sometimes the line number is even wrong.
Security? Template files are only need to be readable?
It's difficult to debug the code.
Code is harder to understand
more .. ?
stream wrappers and include()
I recently read about stream wrappers in php. You even could create your own. A other solution than eval would be to create a custom stream wrapper for every template "format" and use include to parse the template.
This has the following (potential) flaws:
Pro
may solve the problems with showing the wrong file/line-number in error messages (has anyone experiences with this?)
you could handle the template file exactly how to want it to be handled. Full control.
Contra
allow_url_(fopen|include) has to be on?
it is slow? (is eval() slow too?)
no gain in security. include does basically the same thing as eval.
more ... ?
EDIT: cached parsed files and include()
A third option would to to parse the template to PHP code and cache them (as suggested by #Jen-YaKovalev).
Pro
includes caching
Contra
if an error occurs while including the rendered template and an error occurs
the error message doesn't point you to the correct file/eventually shows you
the wrong line number.
You need an extra tmp/ directory to save the parsed files. You need write
permissions for PHP/webserver. Would be more insecure because hackers
would append some malicious code easier.
EDIT: stream filters and include('php://filter')
lately found the following php.net pages:
php://filter: http://php.net/manual/en/wrappers.php.php
strea_filter_register http://fr2.php.net/manual/en/function.stream-filter-register.php
This would be an other possibility to solve this problem. Using include('php://filter/read=filtername/resource=file.php'), I could include a file which would first go through the filter filtername, before it gets executed.
Pro
doesn't need so much code as stream wrappers
Contra
not so much possibilities as with stream wrappers (caching?)
security?
speed?
Question
Have experiences using stream wrappers for parsing template files or similar?
Is there yet an other solution?
Are there more pro's and contras?
Which one would you recommend?
I think it's just a taste of one's coding-style, you'd better vote it or something.
I personnaly think eval is evil (in every language),
had bad experiences with include + php wrappers (even integrated ones*),
knowing all big(gish) template systems use compiling to a php file (smarty, twig), this it the one, i would use.
(*) In an earlier project we used a 1-line code (an empty class-extension) in a data-url wrapped include, and its performance was awful.
You certainly don't want to parse templates at every request on the production environment, it would be a waste of resources and consequently a slow and not a very smart approach, so I'd strongly suggest going with the cached parsed files and include() approach.

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.

Categories