Is there a faster way to include PHP files? - php

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.

Related

How should I include a file where of I know the path, but don't want to use ../?

I want to include a script that I can find in http://localhost/scripts/script.php , but there's something wrong, as we all know: the unclusion of a file using an url is not possible! How can I include a file in the file that's located in http://localhost/admin/employees/create.php?
I do not want to use things like
require_once('../../scripts/script.php');
// or, as that is impossible to do
require_once('http://localhost/scripts/script.php');
So, is there something that I can do so that the system starts from the homedirectory and doesn't interpret the PHP on beforehand?
Thanks in advance for the help you'll provide me!
You can find a lot of info, look inside what´s the best for you, there are differences depending on OS of server:
print_r($_SERVER);
The easiest way to do this, is using the following script:
<?php
$docroot = $_SERVER['document_root'];
require_once($docroot.'/scripts/script.php');
?>
Important! The server has to be well-configured for this method. At least the document_root should be set properly.

$_GET inside include from URL?

i want to include a file, but with $_get, i don't know how to explain but i try to give examples.
I need to include a file from URL like this
mysite.com/?=MYINCLUDETEXT
and to write on <?php include('MYINCLUDETEXT.php'); ?>
Anyone tell me, Thank You.
This will actually do what you want
if (isset($_GET['file'])){
include($_GET['file'].'.php');
}
You might also want to test that the file, you are trying to include exists
file_exists and actually is a file is_file and not a folder.
But you have to understand, that even doing this you are creating a BIG breach in your system and helping people who want to hack your.
Not only it becomes easier to include uploaded files, (not only files which were validly uploaded), but it also allows to include random files from your server.
To avoid problems described in answer above - put all your files names (which should be included) in array, like:
$pages_array=('home','services','contact').
And then check GET var: if(!in_array($_GET['page'], $pages_array) { die(); }
Because you will probably need some other $_GET values/vars, i suggest that you use $_GET['page'] - for inclusion... You could later add mod rewrite to display pages as 'normal' urls... e.g.
www.yoursite.com/index.php?page=contact, could be rewritten to : www.yoursite.com/contact.html

PHP add constant on load before scripts

I was wondering if it possible to add constants to php before any scripts are ran, thus on startup. If this is possible, could it be done with classes etc aswell?
I was thinking in the direction of creating a plugin for php but maybe there is a way simpler way.
I don't mean including a file in every script.
thanks in advance
Not constants as far as I'm aware, but this is ok:
.htaccess
SetEnv MYVAR "hello"
somefile.php
echo $_SERVER['MYVAR'];
See the Apache docs on SetEnv for more.
To directly answer the question, there are two approaches:
Use auto_prepend_file to auto include a PHP file that has define calls.
Configure your web server to set server variables.
I think the second is a better approach. However, I don't see how either of them are very useful in the context of a plugin. Usually a class autoloader of some sort is the way to go there, or to require a single include file.
If I understand your question correctly, what I do is to include a file before all else on my index.php. That same file contains tons of constants, control verifications, initialization for the DB object, etc...
e.g.,
INSIDE index.php
<?php
$moduleRoot = dirname(__FILE__);
require_once($moduleRoot."/components/inc/inc.php");
// continue to render the web page and perform as usual
?>
INSIDE THE inc.php
// When in development, all errors should be presented
// Comment this two lines when in production
error_reporting(E_ALL);
ini_set('display_errors', '1');
// Website id for this project
// the website must be present in the table site in order to get
// the configurations and records that belong to this website
define("CONF_SITE_ID",1);
// Domain path where the project is located
// Should be like the access used on the browser
$serverDomain = $_SERVER["HTTP_HOST"];
$serverAccess = (!empty($_SERVER['HTTPS'])) ? ('https://') : ('http://');
$serverRoot = dirname(__FILE__);
define("CONF_DOMAIN", $serverAccess.$serverDomain);
// etc ...
EDITED
Since you have multiple "startup" files and you need all of them to call inc.php, the best choise seems to be .user.ini as of PHP 5.3.0, you can read about it here!.
And an article on the subject.

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.

PHP include once

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.

Categories