4

如何从 mysql 行“内容”记录中返回 php 代码,其中可能只包含纯文本,例如:

Hello!

或/和 php 之类的:

Lets try some php: <?php echo phpinfo(); ?>

当它只包含纯文本时没有套管速度性能?


这是一个使用 include() 返回 php 的示例,但在这种情况下,这不是我所要求的(我问的是所有内容 php 都来自 mysql 的情况)。

mysql记录:

+---------------+
| id |  content |
|---------------|
|  0 | test.php |
+---------------+

test.php 内容<?php echo phpinfo(); ?>

试图从 mysql 槽中返回 php include() :

$result=mysql_query("SELECT content FROM test WHERE id=0");
while($row=@mysql_fetch_array($result,MYSQL_ASSOC)){
    $row[]=array('row'=>array_map('htmlspecialchars',$row));
    $content=$row['content'];
    ob_start();
    include $content;
    $content=ob_get_contents();
    ob_end_clean();
    echo $content;
}
mysql_close($con);
4

2 回答 2

4

尝试评估记录的内容:eval($row['content']);

补充:您的案例中有一个混合的 html+php 代码,这意味着您需要使用关闭 PHP 标记来离开 PHP 模式,因此在您的特定情况下,这可能看起来像这样:

eval( '?>'. $row['content'] .'<?php ' );

注意:在开始标签后留下多余的空格,因为它有一些问题:http ://www.php.net/manual/en/function.eval.php#97063

于 2011-06-28T19:05:27.423 回答
1

数据库中的 PHP 代码很糟糕,但我之前遇到过必须这样做的情况,因为我的雇主不允许我重写系统以避免它,所以这是我们使用的解决方案的通用版本:

$string = 'this <?php echo "is not"; ?> cool';

function exec_php($php_string) {
    return preg_replace_callback(
        '/<\?(?:php)?(.*)\?>/m',
        'exec_php_embed',
        $string
    );
}

function exec_php_embed(array $args) {
    if (count($args) != 2) {
        return '';
    }
    list(,$code) = $args;
    ob_start();
    eval($code);
    return ob_get_clean();
}

注意:对此要非常小心! 不要执行用户生成的内容! 尝试尽快更换它!

使用eval()不仅效率低下,即使使用不当也会很危险。虽然我非常不鼓励使用上述内容,但我确实认为这将证明是解决您当前问题的方法。我不保证它不会自己产生更多问题;)

正如 GNU 所说:

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
于 2011-06-28T19:13:04.140 回答