$var = require_once("target.php");
is that possible to store require_once in variable and execute it late?
I need to place this into function
function foo($path){
if($path !== ""){$path = require_once($path);}
do something first...
$path//than execute require_once
}
The answer is no. When you assign require_once(); to a variable, the variable turns into a boolean with 1 in case the file was included successfully, or 0 otherwise (useless in require_once() as it returns a fatal error if it fails.
So, doing:
<?php
$hello = require_once("./hello.php");
echo $hello; // Prints 1.
?>
Anyway, if you create a php file that returns something, as for example:
FILE: require.php
<?php
$hello = "HELLO";
return $hello;
?>
In this case, the previous example would be different:
<?php
$hello = require_once("./require.php");
echo $hello; // Prints HELLO.
?>
So, you cannot store the function itself to execute it later, but you can store returned values from the required or included files. Anyway, if you explain better what are you using it for, I maybe able to help you better.
Related
I have a file, let's call it first.php. It echoes a lot of text. Inside that text I also want to include something another file, second.php echoes. I'd like to do this without including the code from second.php, because there are collisions.
TL;DR I want a PHP script to execute another one, wait for it to print, and then echo whatever it printed.
Tried
echo something
include second script
echo something else
But it doesn't work because of said collisions. The second script only prints a short plain text.
Better example
a.php prints "hello" and "world" and declares $i=1
b.php prints "beautiful" and declares $i=2
I want to print "hello beautiful world" and have $i=1
You could run the second script through the CLI with shell_exec
echo something
shell_exec("php second.php");
echo something else
However, this won't work if the second script needs to access variables that are set by the webserver, like $_GET or $_SERVER. If you need to pass certain variables along, you can send them as command line arguments. But the second script will then have to access them using $argv, not $_GET.
shell_exec("php second.php " . escapeshellarg($_GET['id']));
second.php can get the ID from $argv[1].
Imo you should really solve the actual problem by not re-using variables which are sharing scope. If you cannot do that it means you are putting too much in the current scope. However if you really want to do it you could wrap it in a function (which has its own scope).
<?php
$i = 1;
echo 'hello';
echo call_user_func(function() {
// in your case this would be a include statement
$i = 2;
return 'beautiful';
});
echo 'world';
var_dump($i); // 1
If you actually need to "import" variables from the current scope create a closure instead:
<?php
$i = 1;
echo 'hello';
echo call_user_func(function() use ($theVariable) {
// in your case this would be a include statement
$i = 2;
return 'beautiful';
});
echo 'world';
var_dump($i); // 1
You could include the second file in a function. Functions have their own variable scopes. So, variables of the second file can not overwrite variables with the same name of the first script file.
$myvar = 1;
include 'first.php';
callSecond ();
echo $myvar;
function callSecond () {
include 'second.php';
}
echo $myvar would give 1, even when 'second.php' assigns $myvar = 2;
I have a strange question that's probably not possible, but it's worth asking in case there are any PHP internals nerds who know a way to do it. Is there any way to get the variable name from a function call within PHP? It'd be easier to give an example:
function fn($argument) {
echo SOME_MAGIC_FUNCTION();
}
$var1 = "foo";
$var2 = "bar";
fn($var1); // outputs "$var1", not "foo"
fn($var2); // outputs "$var2", not "bar"
Before you say it - yes, I know this would be a terrible idea with no use in production code. However, I'm migrating some old code to new code, and this would allow me to very easily auto-generate the replacement code. Thanks!
debug_backtrace() returns information about the current call stack, including the file and line number of the call to the current function. You could read the current script and parse the line containing the call to find out the variable names of the arguments.
A test script with debug_backtrace:
<?php
function getFirstArgName() {
$calls=debug_backtrace();
$nearest_call=$calls[1];
$lines=explode("\n", file_get_contents($nearest_call["file"]));
$calling_code=$lines[$nearest_call["line"]-1];
$regex="/".$nearest_call["function"]."\\(([^\\)]+)\\)/";
preg_match_all($regex, $calling_code, $matches);
$args=preg_split("/\\s*,\\s*/", $matches[1][0]);
return $args[0];
}
function fn($argument) {
echo getFirstArgName();
}
$var1 = "foo";
$var2 = "bar";
fn($var1);
fn($var2);
?>
Output:
$var1$var2
I'm going to pass through some values between two required/included php file,ex:
mysql.php:
<?php
$conn = mysql_pconnect("mysql.host.com","root","password") or trigger_error(mysql_error(),E_USER_ERROR);
?>
fun.php:
<?php
function fun() {
mysql_select_db($conn);
}
?>
main.php:
<?php
require_once('mysql.php');
require_once('fun.php');
fun();
//Output: Error that can't find $conn
?>
Sorry that I describe too simple. I found that I can pass anything though two included files if code run directly. But if one of them write as a function(like fun.php), the fun() can't read mysql.php's value. Anyone can give me a solution? Forgive my bad English and poor knowledge of PHP > <
Update:
One of solution I found is to insert the mysql.php's code in each functions like:
fun.php:
<?php
function fun() {
$conn = mysql_pconnect("mysql.host.com","root","password") or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($conn);
}
?>
But the problem is it's very very annoying(because I've wrote huge of functions) and maybe not safe because it stored username and password of the mysql server.
Your question is very confusing. If I understand it, then the answer depends on how you are using the included information.
If you need to use the variables in functions, you need to declare the variable as "global" at the beginning of the function (or Class if you are OOP).
For example, if your main.php file defines the following example function:
function exampleFunction()
{
global $var1; //from inc1.php
global $var2; //from inc2.php
//now do something with the variables and probably return a result
}
If you are coding OOP,
class SomeClass
{
global $var1; //from inc1.php
global $var2: //from inc2.php
private $var3; //local to this class
}
try using globals $var1 can be called as
$GLOBALS['var1'];
or
$_GET['var1'] = 1;
$var2 = $_GET['var1'];
I would like to use "dynamic" $_POSTs, I don't know if I am using the right term but in other words I would like to use for example $_POST[$dynamic_variable] in a function that is in an included file. Because the $dynamic_variable isn't recognized or because I can't use $_POST[something] in included files it doesn't work and I get an error message like Undefined variable: lastname in filename.php.
What is the safe to way to use $_POSTs in included files and when the $_POST[name] is variable?
Thank you!
///// updated - piece of code ///////
[code.php]
include("functions.php");
$test_arr = array(
"10|field_name1|500",
"20|field_name2|750",
...
);
checkForm($test_arr);
[functions.php]
function checkForm($test_arr) {
foreach ($test_arr as $test) {
$test_details = explode("|", $test);
$field_name = $test_details[1];
echo $_POST[$field_name];
}
}
The $_POST array is available in all included PHP files. Normally, the $dynamic_variable is also available, if you do it like so:
$dynamic_variable = 'test';
include('include.php');
// in include.php:
echo $_POST[$dynamic_variable];
But when declaring the $dynamic_variable inside a function or class, you don't have access to it outside. You could also declare it as global or hand it over as a parameter. Please also read the documentation about variable scope.
I would not write if it is smart to use globals like that or not.
Your problem is you tried to access a variable which does not exists, as the error message said.
To avoid the error message, you can do:
if(isset($_POST[$your_var_name]){
//do something with $_POST[$your_var_name]
}
I hava a function that looks something like this:
require("config.php");
function displayGta()
{
(... lots of code...)
$car = $car_park[3];
}
and a config.php that look something like this:
<?php
$car_park = array ("Mercedes 540 K.", "Chevrolet Coupe.", "Chrysler Imperial.", "Ford Model T.", "Hudson Super.", "Packard Sedan.", "Pontiac Landau.", "Duryea.");
(...)
?>
Why do I get Notice: Undefined variable: car_park ?
Try adding
global $car_park;
in your function. When you include the definition of $car_park, it is creating a global variable, and to access that from within a function, you must declare it as global, or access it through the $GLOBALS superglobal.
See the manual page on variable scope for more information.
Even though Paul describes what's going on I'll try to explain again.
When you create a variable it belongs to a particular scope. A scope is an area where a variable can be used.
For instance if I was to do this
$some_var = 1;
function some_fun()
{
echo $some_var;
}
the variable is not allowed within the function because it was not created inside the function. For it to work inside a function you must use the global keyword so the below example would work
$some_var = 1;
function some_fun()
{
global $some_var; //Call the variable into the function scope!
echo $some_var;
}
This is vice versa so you can't do the following
function init()
{
$some_var = true;
}
init();
if($some_var) // this is not defined.
{
}
There are a few ways around this but the simplest one of all is using $GLOBALS array which is allowed anywhere within the script as they're special variables.
So
$GLOBALS['config'] = array(
'Some Car' => 22
);
function do_something()
{
echo $GLOBALS['config']['some Car']; //works
}
Also make sure your server has Register globals turned off in your INI for security.
http://www.php.net/manual/en/security.globals.php
You could try to proxy it into your function, like:
function foo($bar){
(code)
$car = $bar[3];
(code)
}
Then when you call it:
echo foo($bar);
I had the same issue and have been tearing my hair out over it - nothing worked, absolutely nothing - until in desperation I just copied the contents of config.php into a new file and saved it as config2.php (without changing anything in its contents at all), changed the require_once('config.php'); to require_once('config2.php'); and it just started working.