开发者

PHP code dynamic evaluation

开发者 https://www.devze.com 2023-03-25 07:00 出处:网络
Imagine we have 2 files, one called 1.php with the following code: <?php $hello = \"Hello from 1\"; ?>

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 ;)

0

精彩评论

暂无评论...
验证码 换一张
取 消