PHP code dynamic evaluation - php

Imagine we have 2 files, one called 1.php with the following code:
<?php
$hello = "Hello from 1";
?>
and 2.php with the following code:
<?php
function LoadPage( $page )
{
$f = fopen( $page, 'r+' );
$content = fread( $f, filesize($page) );
fclose( $f );
return $content;
}
function GetEvalContent( $content )
{
$var = "";
ob_start();
eval( "?>" . $content . "<?" );
$var = ob_get_contents();
ob_end_clean();
return $var;
}
$hello = "hello from 2";
echo $hello . '<br/>';
$content = LoadPage( '1.php' );
GetEvalContent( $content );
echo $hello;
?>
So what the 2.php does is load the content of 1.php and evaluate the php code inside it. Now what I want to do is during the evaluation of 1.php, variable $hello changes to "hello from 1". However if you execute 2.php you always get:
"hello from 2"
"hello from 2"
instead of getting
"hello from 2"
"hello from 1"
Has anyone encountered this problem before and if so, how would you fix it?

There is a much easier way to do this. Use PHP's include.
1.php
<?php
$hello = "Hello from 1";
?>
2.php
<?php
$hello = "hello from 2";
echo $hello;
include '1.php';
echo $hello;
?>
UPDATE (not tested):
function includeFile($file){
global $hello; // Use the global variable $hello
// this will make the include sets $hello correctly
ob_start();
include $file; // Remember any variables set here will be in this scope,
// not the global scope (unless you add them to the global line above)
$var = ob_get_contents(); // This will contain anything echoed to the screen
// from the included file
ob_end_clean();
return $var;
}
$hello = "hello from 2";
echo $hello;
$file = '1.php';
$output = includeFile($file);
echo $hello;
echo $output;

You're doing your eval() within a function, so the $hello in the included file will be part of only the function's scope. It will not affect the $hello that's defined outside the function (which is global scope).
You'd need to put the global keyword into your included file, unless you want to write your own PHP parser to figure out what variables are being defined in the included file and auto-globalize them.
However, in the bigger picture... WHY? eval is a horribly evil ugly construct, and you're opening yourself up to a world of debugging pain, let alone the security issues.

Have you considered using require or include? PHP Manual
Example:
$hello = "Hello from 2";
echo $hello;
include("1.php");
echo $hello;

try to use $GLOBALS['hello'] instead of $hello
PS: Don't forget eval is evil ;)

Related

php call variable and put back on while loop

sorry for my last question where i try put some live code with ob_start buffer content is not helping me to solve my problem because buffer content just collects output text, it doesn't execute any code. thanks #akrys for your advices
what i want is to put code into while looping like this
$sql = $conn->query("SELECT * FROM `users`");
$var = $row['full_name'];
include('test.php');
after i call test.php contain while code like:
while($row = $sql->fetch_array()) {
echo $var;
}
everything is work if i replace $var with $row['full_name'];
but i get the name of row field from some script on index.php so i should access that file first then i call portable file contain query to fetch_array on test.php
how to make it work when i put it back with $var contain variable field name
thank you very much for your attention guys
you should to include before your code
page
test.php
<?php
$someVariable = 'hello'; // the variable only can access in here
?>
<?php
include('test.php');
ob_start();
echo "some text with call variable $someVariable";
echo "other stuff";
$tdcol1_val = ob_get_contents(); ob_clean();
echo $tdcol1_val; //
?>
of course you can use define too
page test.php
<?php
define( "SOMEVARIABLE", hello );
?>
<?php
include('test.php');
ob_start();
echo "some text with call variable ".SOMEVARIABLE;
echo "other stuff";
$tdcol1_val = ob_get_contents(); ob_clean();
echo $tdcol1_val; //
?>
you can use:
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
for more help, use the link below:
enter link description here

How to get the value from include statement in a variable?

Suppose I write a line
include Yii::app()->basepath.'/views/email/email_friend.php';
now how can i take the response of this line into a variable?
like
$abc = include Yii::app()->basepath.'/views/email/email_friend.php';
Have a look at the PHP docs for include http://php.net/manual/en/function.include.php
Example #5 is I think what you're looking for
return.php
<?php
$var = 'PHP';
return $var;
?>
noreturn.php
<?php
$var = 'PHP';
?>
testreturns.php
<?php
$foo = include 'return.php';
echo $foo; // prints 'PHP'
$bar = include 'noreturn.php';
echo $bar; // prints 1
?>
All you have to do is the included file had a return with the desired value. It's been quite popular for some time.
so the include.php should like the following:
<?php
return ' World!';
and the including one:
<?php
$a = include('include.php');
echo 'Hello'.$a; // Hello World!
When you include it's like you're copy/pasting the code into your PHP. If it's just inline PHP and there was a variable $abc in the include file 'email_friend.php' then you could access the variable normally after the include.
I know this is an old post. I hope my answer will be useful to someone. I combined the Accepted answer with the answer "PHP/7 you can use a self-invoking anonymous function..."
define( 'WPPATH', dirname(dirname(__FILE__)) . '/public/partials/bla-bla.php' );
$publicDisplayContent = (function () {
// [PHP/7 you can use a self-invoking anonymous function](https://stackoverflow.com/a/41568962/601770)
// https://stackoverflow.com/a/5948404/601770
ob_start();
require_once(WPPATH);
return ob_get_clean();
})(); // PHP/7 you can use a self-invoking anonymous function
error_log( 'activate() >> $publicDisplayContent: ' . print_r( $publicDisplayContent, true ) );
DOT DOT DOT
'post_content' => $publicDisplayContent,

Using fetch() without Smarty?

Smarty 3 has an option to set (assign) a variable and then include (fetch) a file to a new variable.
How can I do this without the Smarty class? file_get_contents would not work, is there something else?
For example, this is the Smarty code:
<?php
$variable = 'Hello World';
$smarty->assign('variable', $variable);
$content = $smarty->fetch('content.tpl'); // content.tpl have "{$variable}" inside
echo '<script>document.write("' . $content . '")</script>'; // this will output <script>document.write("Hello World")</script>
?>
I want to do it without Smarty:
<?php
$variable = 'Hello World';
$content = file_get_contents('content.php'); // content.php have "echo $variable;" inside
echo '<script>document.write("' . $content . '")</script>';// this needs to output <script>document.write("Hello World")</script>, but it's outputing echo $variable;
?>
You can take advantage of buffering tricks.
function fetch($filename, array $vars) {
ob_start(); // Start output buffering
extract($vars); // Extract variables
require($filename); // Include a file
return ob_get_clean(); // Pass variables to included filename and return output as a string
}
And then you can use it like this:
$content = fetch('content.php', array(
'variable' => 'Hello World',
'name' => 'John Doe',
));
echo $content;
My content.php looks like as follows:
<div>
<b><?php echo $variable; ?></b>, you're logged in as <?php echo $name; ?>
</div>
It outputs Hello World, you're logged in as John Doe

How to pass the require_once output to a variable?

I want to call require_once("test.php") but not display result and save it into variable like this:
$test = require_once('test.php');
//some operations like $test = preg_replace(…);
echo $test;
Solution:
test.php
<?php
$var = '/img/hello.jpg';
$res = <<<test
<style type="text/css">
body{background:url($var)#fff !important;}
</style>
test;
return $res;
?>
main.php
<?php
$test = require_once('test.php');
echo $test;
?>
Is it possible?
Yes, but you need to do an explicit return in the required file:
//test.php
<? $result = "Hello, world!";
return $result;
?>
//index.php
$test = require_once('test.php'); // Will contain "Hello, world!"
This is rarely useful - check Konrad's output buffer based answer, or adam's file_get_contents one - they are probably better suited to what you want.
“The result” presumably is a string output?
In that case you can use ob_start to buffer said output:
ob_start();
require_once('test.php');
$test = ob_get_contents();
EDIT From the edited question it looks rather like you want to have a function inside the included file. In any case, this would probably be the (much!) cleaner solution:
<?php // test.php:
function some_function() {
// Do something.
return 'some result';
}
?>
<?php // Main file:
require_once('test.php');
$result = test_function(); // Calls the function defined in test.php.
…
?>
file_get_contents will get the content of the file. If it's on the same server and referenced by path (rather than url), this will get the content of test.php. If it's remote or referenced by url, it will get the output of the script.

Get contents of php file after it's ran/executed

How can I put the result of an include into a PHP variable?
I tried file_get_contents but it gave me the actual PHP code, whereas I want whats echoed.
Either capture anything that's printed in the include file through output buffering
ob_start();
include 'yourFile.php';
$out = ob_get_contents();
ob_end_clean();
or alternatively, set a return value in the script, e.g.
// included script
return 'foo';
// somewhere else
$foo = include 'yourFile.php';
See Example 5 of http://de2.php.net/manual/en/function.include.php
or simply return a value from an included file as explained here.
return.php:
<?php
$var = 'PHP';
return $var;
?>
$foo = include 'return.php';
echo $foo; // prints 'PHP'

Categories