PHP include once - php

Is it more efficient to use PHP's include_once or require_once instead of using a C-like include with a header guard?
I.e,
include_once 'init.php';
versus
include 'init.php';
//contents of init.php
if (!defined('MY_INIT_PHP')) {
define('MY_INIT_PHP', true);
...
}

"require_once" and "include_once" are generally a bit slower that just "require" and "include" because they perform a check wether the file has already been loaded before.
But the difference only matters in really complex applications where you should do autoloading anyway and by that would not need require_once/include_once, if your autoloader is well coded.
In most simple applications, it's better to use the require_once/include_once for convenience reasons.
The header guard approach is just messy code that should be avoided. Just imagine, if you forgot that check in one of many files. Debugging that could be a nightmare.
Just use autoloading if your application is suitable for it. It's fast and the most convenient and clean way.

I would expect include_once to be faster than using header guard inside the included file, since you still need to open and load the file in the latter.

You could try it 10,000 times with a timer, but I think defining MY_INIT_PHP is infinitesimally faster.
To be honest, it's likely such a small difference that there's no practical need to care unless you're working for sites like Facebook.

I always use REQUIRE_ONCE if script contents is unique.

Related

include_once when using header files

Quick question, I have:
include_once("connection.php");
within my header and then on my internal pages I have:
<?php include 'header.php';?>
Do I still need to add:
include_once("connection.php");
on my internal pages? The reason I ask is: Right now I only have it within the header and sometimes my forms will save to the database and sometimes they will not. I'm just trying to find out what the best practice is.
No, includes are made "recursively".
FYI : "include" is faster than "include_once" because it doesn't check for included files
I usually do it manually, with a call to require() instead:
index.php
require("Config.php")
$c = Config();
Config.php
<?php
if(!DEFINED("CLASS_CONFIG_PHP__")) {
DEFINE("CLASS_CONFIG_PHP__", 1);
// All library code here
}
?>
This way, I'm sure everything is only defined once, and require will make sure the included file has no errors (will fail at that line if there are errors in it).
include_once() will include a file only once regardless of how many times you call it with the same parameter. include() will throw an error if its called twice with the same parameter.
if you have include('connection.php') in your header and all internal pages use this header then you wont need to include this in internal pages too.
However, it is bad practice to mix view layer with business logic layer. Read a bit on MVC patterns and how to use it. Connection should be done in a back end where all the database functions are called. Once header.php is called then you are in rendering mode and you should only be rendering content at that stage.

Is there a faster way to include PHP files?

I have the following code when I want to include some code from another PHP file:
$domain = 'www.example.com';
require_once $domain.'/footer.php');
I wonder though if this is slower than it could be, because surely this then has to go through a DNS to find the page?
Is there a quicker way to do this? Maybe I should set my IP as $domain? Or maybe there is some PHP snippet that will detect it for me?
I also pay for DNS hits, so there's that too...
No thought You can include file via autoloader but there is no other way to include files than
Require and include in php and both are fast, even if you use temples it would be same.

Why is wp-blog-header is seperate from index?

What it the advantages of having the code in wp-blog-header.php seperate from index.php in wordpress?
I tried to move the code in wp-blog-header.php to index.php and the website loads perfectly fine, I think.
Could someone please explain about the advantage of running a require function in index to call wp-blog-header instead to writing the wp-blog-header code in index
Code reuse. There is not only index.php as entry-script. Every entry-script that wan't to load Wordpress core library functionalities and templating functionalities can require that file.
Using require/include(_once) is the historic way in PHP to do code-reuse.
include has/is often used for (HTML) tamplating code.
require is more often used for PHP program code, like function and class definitions.
These are not rules set in stone, it's more what common usage patterns are. Both are very close to each other:
Difference between require, include and require_once?
Difference between "include" and "require" in php

How to achieve "application scope variables" in php?

I am working on a new PHP project now, this time I want to get the basics right at the beginning. Previously I've found requiring/including files in php a bit of pain, please consider the following structure:
/application_root/index.php
/js/...
/css/...
/php/...
/conf/...
...
In the index.php I can certainly use something like:
<link rel="stylesheet" href="css/sample.css" ... />
<script type="text/javascript" src="js/sample.js"></script>
To refer to the included css and js, or even php snippets. However, this would only work in the index.php which resides under the root of my application folder. I reckon this is no good.
I came across Java application configuration file "web.xml" where you can define application scope variables that you can simply refer to. .NET with C# has a similar thing. How to achieve this in simple php code so that from any php file in my app, I can type:
<?php echo "<link href='".$application_root_url."/php/sample.css' ..."; ?>
And it will evaluate to the right location?
I am thinking to use:
Global variables <== bad practice as violation to OOP? I stop doing this since c programming;
set_include_path <== so php will look for it, requires unique name and proper naming convention?
load variables from ini files? <== how to make this happen?
any new thoughts?
You don't want to use global variables because they break encapsulation.
set_include_path will do no good especially if you are using those variables in HTML, because the include_path is relative to the application's filesystem path and not to its base url.
Determining the application base paths is generally not done from a configuration file, as it easy to detect when your application has a gateway script. Since those are constant values, it makes sense to define a constant:
define('APP_ROOT', dirname(__FILE__));
define('APP_URL', dirname($_SERVER['PHP_SELF']));
If you want to parse INI files however, you could use parse_ini_file, or parse_ini_string (>=5.3.0):
$config = parse_ini_file(APP_ROOT.'/'.CONFIG_DIR.'/database.ini');
echo $config['host'];
The path here is a URI--not a filesystem location. You may be trying to go about this the wrong way anyway.
You have to use relative path. So just "/css/sample.css" instad of "css/sample.css".
That would than always load from yourdomain.com/css/sample.css even if your .php is in yourdomain.com/somefolder/file.php
The PHP script only produces an output that the browser interprets. And the scope is the URL in the browser not on the filesystem.
So the value of the $application_root_url variable is for the browser not for the PHP script!
If you want to use INI files, you can use the parse_ini_file() function of PHP.
no reason for using global variables except for lazy coding
is not efficient, and PHP will get harder to figure which file to be included if two same filename on different path
parse_ini_file is what you looking for
However, I prefer using constant, I did not ask to define constant everywhere, just put all your essential path into a config file, and require that at the beginning on your application.
Some might say constant is slow, comparing using class constant which might require you to include multiple files, which does better ? And the best things is once constant defined, no-one or code can override it.
example to illustrate
define('css_root', '/home/user/apache/css'); <-- server absolute path
define('css_web_root', '/css'); <-- web root, for HTML
define('css_cache_root', '/cache/css'); <-- cache directory
You might want to try something like the MVC pattern. As an example the ZendFrameworkds MVC passes a variable $this->base_url to the views. The views are where you HTML resides so you will be able to do the following in the view:
<link rel="stylesheet" href="<?php echo $this->base_url; ?>/css/sample.css" ... />
Your problem is exactly the reason that led me to the MVC pattern and it's many advantages.

PHP include() alternative?

I want to know if my code is safe and if there are other safer alternatives to include external files..
So this is my code example, is it safe? How can I make it safer? Thanks!
<?php switch($_GET['p']){
case 'test1':
include 'test1.php';
break;
case 'test2':
include 'test2.php';
break;
case 'test':
echo 'something';
include 'pages/test.php';
echo 'something';
break;
default:
include 'main.php';
break;
} ?>
You code is fine. There is no issue conditionally including files like you are doing as the file names are hardcoded. The issue occurs when a the file included is based on an un-sanitized value from the user. E.g
include $_GET['p'];
Which can include whatever the user wants (depending on PHP settings it may also include files on other domains)
The other options are variations on what you are doing
require
require_once
include_once
require and require_once will fail if the file doesn't exist. inlucde_once and require_once ensure that the file is only included once, so it that file has been inlucded elsewhere in the program it won't be included.
include_once 'myfile.php';
include_once 'myfile.php'; //does nothing as the file is already included
If you have use classes, there is also the option of the autoloader. From the looks of your application you would have to re-structure it to be able to use it though.
You might consider examining the contents of $_GET['p'] prior to even entering the switch. If it contains special characters, rubbish or something else, your program may want to log the incident (and not waste time trying to render the page).
At the least, a nice and polite "Sorry, we could not process your request" page would be in order.
This still allows the switch to fall through to the main page, provided that p contained something worthy of the switch evaluating in the first place.
This is especially true if the main page does any amount of queries in order to render. Sooner or later, someone will notice your URI structure and decide that it might be fun to play with it, don't burn CPU cycles on idiots :)
Seeing as you only include those you've hardcoded, I don't see why this wouldn't be safe. These aren't external files though, but I see what you mean. External would mean on a different server.
As for your question, the only alternative to include is require but that isn't necessarily safer, it just works differently.
Yes, perfectly safe.
You're including files you know the contents of, and not doing it based on variables coming from outside sources. an include wont cause your script to fail if it can not load, if that is the result you'd want, choose require('filename');.
It is safe as it is and the switch statement made the logic clearer. Just to make it more safer maybe you can use $__POST just to hide the switch variable data source to make it little bit safer. :D
You could make that more readable, as follows:
$safeIncludes = array('test1', 'test2', 'test3');
$p = $_GET['p'];
if(in_array($p, $safeIncludes)) {
$scriptName = $p . '.php';
include($scriptName);
}
Other than that it is safe as others have pointed out.

Categories