2012-09-03 40 views
1

我有2种存储页面的方法。第一个很简单,将其存储在一个文件中。第二个是将它存储在我遇到问题的数据库中。
整个“系统”基于一个“引擎”,它通过将页面注入HTML模板来输出页面。简单来说:代码必须在到达引擎之前执行。希望这会使一些代码更有意义。
page.class.php执行存储在数据库中的PHP代码

... 
// Page was found in the database 
      $this->name = $pageVariables['name']; 
      $this->requiredAuth = $pageVariables['requiredAuth']; 
      if ($parsed) { 
       ob_start(); 
       echo $pageVariables['content']; 
       $this->contents = ob_get_clean(); 
       var_dump($this->contents); 
      } else { 
       $this->contents = $pageVariables['content']; 
      } 
... 
// File exists on the system, load it 
       $fileContents = file_get_contents($this->url); 
       if ($parsed) { 
        ob_start(); 
        include($this->url); 
        $this->contents = ob_get_clean(); 
var_dump($this-contents); 
        if (isset($pageName)) { 
         $this->name = $pageName; 
        } 
        if (isset($requiredAuth)) { 
         $this->requiredAuth = $requiredAuth; 
        } 
        if (isset($useEngine)) { 
         $this->useEngine = $useEngine; 
        } 
       } else { 
        $this->contents = $fileContents; 
       } 

if ($parsed) {...}有如此的页面可以获取的未解析进行编辑。
显然这是一个减少版本,但我希望显示足够。
如果我从数据库中加载一个页面的代码

Hello World<br> 
<?php echo 'Hello World'; ?> 

输出我得到的是

Hello World<br> 
<?php echo 'Hello World'; ?> 

然而,存储在文件输出

Hello World 
    Hello World 

我相同的代码尝试使用eval(),但这只会评估PHP代码,并且在包含HTML/PHP混合时失败。
也许有更好的方法来解决这个问题(存储它,执行等),但这是我目前看到的问题。

+0

就我所知,'eval'适用于HTML/PHP。 –

回答

4

您可以使用PHP's eval来运行存储在数据库中的代码。

$code = get_code_from_db(); 
eval($code); // will evaluate (run) code stored in $code variable 

虽然小心点。 eval是一个需要仔细对待的功能。如果您不考虑存储代码的含义,它可能是错误,安全漏洞的根源,您将其命名。

+0

由于你提到的原因,我希望不要使用'eval()',但即使如此,它也不适用于我:'解析错误:语法错误,/var/www/cms/includes/page.class中意外的T_STRING .php(71):线1上的eval()'d代码' –

+0

这不起作用,因为您的数据库中可能存储了SYNTAX ERROR。您将需要'eval'来运行PHP代码。否则你将无法做到这一点。除非您采用VEEEERY DIFFERENT方法。 (即在数据库中使用模板并在PHP上解析/处理它们,而不是PHP直接编辑) –

+0

编辑:如果我在开始处添加'?>''',它就可以工作,这不是什么大问题。我使用的代码在数据库和文件中是一样的:'Hello World
<?php echo'Hello World'; ?'',但是如果代码是'echo'Hello World';',使用'eval()'似乎只能工作。我想我将不得不看看任何替代品。 –

1

小心eval,this is a good post on why

更好的解决方案是将页面模板存储在数据库中,然后在PHP中安全地解析它们。

相关问题