I have a PHP function which requires authorization for a SOAP request to get the data and processes it. I like to keep the username/password outside of the program in auth.php and use an include statement like this:
include 'auth.php'; // Contains $username and $password.
I normally use include statement at the top of PHP programs. But I don't want to have to pass the values to the function so I put the include statement inside the function.
Does this slow down the program because it's reading auth.php each time the function gets called or does PHP read in all include files and keep the resident in the program, therefore not reading in the same auth.php file each time this function is called?
I have considered using DEFINE instead of setting the variables for username/password so they would be accessible through-out the program, but wasn't sure if this was necessary or not. Thanks!
While I really agree with what #Twisted1919 wrote in the comments, and I think you should listen to his advice, I'd also like to answer your question (does it slow down the execution?).
I'd say "not significantly", for a very simple reason: SOAP, even if done locally, hides XML encoding and parsing. Add to that the "processing of data" that you've mentioned, and you see that the overall work done by the function should amount to far more work than reading and parsing a PHP file that (presumably) only defines a few variables. Hence, that part is really insignificant.
Related
Before I explain the issue, I know the risks of using eval, but there is no realy other way to do it on how my system is build, and it also is for a personal project only. (its a custom cms which when I publish it makes the physical files for me, I just made it though db so I don't need to upload files when not working remote and it is just easy).
Lets explain my issue, I have a main php file which handles all pages, all pages are stored in the db with code and all and is being executed through eval.
And the system also has a function include_db which basicly does the same as include from php normaly just from the db.
But when I access a variable defined in the first eval (main page) it can not be read out in the included eval from the db.
Weird thing is that functions can be read out though the second eval.
Any way to access variables normaly from the included eval that is being generated in the eval of the main page?
(I think it has to do because those variables are not global and its being executed in a function but I do not know a way to make every variable global :( )
Thanks in advance!
The code that is being evalled on the main page:
$skill = isset($_REQUEST['skill']) && is_string($_REQUEST['skill']) && isValidSkill($_REQUEST['skill']) ? $_REQUEST['skill'] : 'overall';
if(!isset($_REQUEST['player']))
include_db('highscore_overview');
else
include_db('highscore_player');
And inside the include of overview I dump the get_defined_vars() and that doesn't return the $skill I set before the include only the variables that are declared in the main index.php (database and such)
First of all a disclaimer: You should never ever execute code from a database. That is a big security risk. It means that whenever someone is successful in gaining access to your database (using sql-injection for example) is now also capable of executing arbitrary code in php by changing the code in your database. You really should not do that!
If you are using code from the database to implement custom (email-)templates, please consider using a templating-engine for that like twig. Most syntaxes of template-engines are built in a way that you cannot break out of them and execute arbitrary code like you could with raw php code.
That said, i now try to answer the original question (because i cannot stop you doing things you should not do anyways). In terms of variable-scope, eval behaves like a function. If you want the variables defined inside it global, you have to manually make every variable defined inside the eval global.
You can do that by append a code-snippet to every code executed in eval that takes every local (in eval defined) variable and writes it into global scope.
<?php
function include_db() {
# ... get $code from db here ...
# get's executed after code from db, globalizes all variables
$code .= ';foreach (get_defined_vars()) as $newGlobalName) {';
$code .= ' $GLOBALS[$newGlobalName] = $$newGlobalName;';
$code .= '}';
eval($code);
}
I am new to PHP and very likely I am using the incorrect approach because I am not used to think like a PHP programmer.
I have some files that include other files as dependencies, these files need to have global code that will be executed if $_POST contains certain values, something like this
if (isset($_POST["SomeValue"]))
{
/* code goes here */
}
All the files will contain this code section, each one it's own code of course.
The problem is that since the files can be included in another one of these files, then the code section I describe is executed in every included file, even when I post trhough AJAX and explicitly use the URL of the script I want to POST to.
I tried using the $_SERVER array to try and guess which script was used for the post request, and even though it worked because it was the right script, it was the same script for every included file.
Question is:
Is there a way to know if the file was included into another file so I can test for that and skip the code that only execute if $_POST contains the required values?
Note: The files are generated using a python script which itself uses a c library that scans a database for it's tables and constraints, the c library is mine as well as the python script, they work very well and if there is a fix for a single file, obviously it only needs to be performed to the python script.
I tell the reader (potential answerer) about this because I think it makes it clear that I don't need a solution that works over the already existant files, because they can be re-generated.
From the sounds of it you could make some improvements on your code structure to completely avoid this problem. However, with the information given a simple flag variable should do the trick:
if (!isset($postCodeExecuted) && isset($_POST["SomeValue"]))
{
/* code goes here */
$postCodeExecuted = true;
}
This variable will be set in the global namespace and therefore it will be available from everywhere.
I solved the problem by doing this
$caller = str_replace($_SERVER["DOCUMENT_ROOT"], "", __FILE__);
if ($_SERVER["REQUEST_METHOD"] === "POST" and $caller === $_SERVER["PHP_SELF"])
performThisAction();
Let's say I have a PHP file some_function.php which I can run with file_get_contents('some_function.php?' . $parameters_string) (or any similar function). The parameters to this function can be given via either GET or POST HTTP method.
Instead I could include needed file and use this function within one script.
I could figure out that it could be reasonable if I need to run a separate process or I need this function to be on a separate server. But if not, is there any reasons not to do it? May be this call will be much slower? Anything else I should take into account?
I know that I will not be able to use global variables (which I assume as a bad coding style anyway).
By using file_get_contents() you will not be actually calling the function in question but will make an HTTP request passing some predefined parameters which will then be passed on the function in your code.
Using include() you could have a library of classes or functions inside that file, and call them directly as needed and as many times as needed.
EXAMPLE:
library.php
function my_function_1() { }
function my_function_2() { }
index.php
include('library.php');
my_function_1(); // call the first function
my_function_2(); // call the second function
my_function_1(); // call the first function again, just because we can
You wouldn't be able to do that through the HTTP request and even if you did hardcode your some_function.php file to do some functionality like above, you would end up with really bad code that would be hard to customize to your needs and near impossible to maintain once it gets bigger.
You cannot pass a query string via a local file_get_contents call as shown.
If you use file_get_contents on a remote HTTP URL, you will be able to use a query string, but this will be significantly slower than a local include or file_get_contents.
You can, incidentally, still include something that needs $_GET/$_POST variables:
<?php
$_GET['something'] = true;
include('something.php');
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.
Suppose you have access to a script which will print or echo an ID string, given a name string, i.e., something like:
http://www.example.com/script.php?name=aNameString
outputing an ID string.
I want to create a script which will allow me to retrieve anIDString, given that I already have a variable holding aNameString, i.e., something like this pseudocode:
$name="Homer Simpson";
$id='www.example.com/script.php?name=$name';
Can you help me understand how I'd do this? ... Thanks, as always!
If you are writing code on the same domain, for security reasons you might consider the include() or require() functions instead, and implementing what you need as a function in php. This way, there is no risk to your server being fed rubbish data and crashing your application.
If you need to pull data from another script do so with care, especially a server that isn't trusted. That said, you can do it with either: http://uk.php.net/curl or http://us2.php.net/manual/en/function.file-get-contents.php, the latter of which looks easier to me.
Try requiring the file, but remember, you'll need to call the function later.
<?php
$name = 'Homer Simpson';
require 'script.php';
?>
That will make the global variable $name, accessible by script.php
However, if it isn't your server, you will need to use a tool like curl to fetch the page.
In the simplest case, you can use the HTTP wrappers to get the output:
$html = file_get_contents('http://www.example.com/script.php?name=aNameString');
and them take the $html apart, unless you meant something different by "outputing an ID string", it output raw text and not html.