gpt4 book ai didi

php - 在不使用 eval() 的情况下从数据库记录运行 php 脚本

转载 作者:行者123 更新时间:2023-11-29 00:06:18 33 4
gpt4 key购买 nike

我想知道如何在不使用 eval() 的情况下运行存储在数据库中的 php 脚本。

预期流程如下

When user POST a string which contains {{typed_alias }}, the system will search the table whether this alias has record in the alias column.

If yes -> replace what user typed with the correspond script which is stored in the replacement column.

If not -> show the original string including {{ wrong_alias }}

预期结果如下

When user posts
Hello, {{morninggg}}, the current unix time is {{nowTime}}

Array output from db

array

 0 =>
array
'ID' => 445
'alias' => 'morning'
'replacement' => 'Good morning'
1 =>
array
'ID' => 446
'alias' => 'nowTime'
'replacement' => time()
2 =>
array
'ID' => 447
'alias' => 'tommorowNow'
'replacement' => time()+86400

Return

Hello, {{morninggg}}, the current unix time is 147855220

现在我已经使用foreach 解决了数据库数组问题,也可以使用str_replace() 将别名替换为脚本。

我用来从数据库中获取数据并进行替换的当前类如下

class replace {
public $definitions;

public function setDefinitions($definitions) {
$this->definitions = $definitions;
}

public function tag($input) {
if($this->definitions && is_array($this->definitions)) {
foreach ($this->definitions as $definition) {
if($defintion['alias'] == 'time') {
$input = str_replace('{{' . $definition['alias'] . '}}', date('Y-m-d'), $input);
} else {
$input = str_replace('{{' . $definition['alias'] . '}}', $definition['replacement'], $input);
}
}
}
return $input;
}
}

当前使用方法

$replace = new replace();
$replace->setDefinitions($tagEngine);
$parsedString = $replace->tag($__input);

//$__input is what user POST to the server

echo $parsedString;

然而,目前的结果如下

Hello, {{morninggg}}, the current unix time is time()

脚本无法在页面运行成功

但是当我像这样手动给出定义时

$definition = array('morning' => 'Good Morning', 'nowTime' => time());
foreach ($definition as $key => $value)
$source = str_replace('{{' . $key . '}}', $value, $source);
return $source;

脚本可以运行并返回

Hello, {{morninggg}}, the current unix time is 147855220

我知道使用 eval() 可以运行脚本,但是,人们认为它在实际应用程序中是一种危险的方法。

谁能给我建议如何处理这个问题?

谢谢!

最佳答案

你不应该使用像 eval() 这样的函数来解决这个问题。您应该从数据库中提取所有 php 代码并按如下方式解析不同的别名(我刚刚更改了 replace 类中的 tag() 方法:

public function tag($input) {
if($this->definitions && is_array($this->definitions)) {
foreach ($this->definitions as $definition) {
$replacement = $definition['replacement'];
switch($definition['alias']) {
case 'nowTime':
$replacement = date('Y-m-d');
break;
case 'tommorowNow':
$replacement = date('Y-m-d', (time() + 86400));
break;
}
$input = str_replace('{{' . $definition['alias'] . '}}', $replacement, $input);
}
}
return $input;
}

如您所见,对于每个 php 代码别名,您可以在 switch() 语句中添加另一个 case。您可以在以下链接中阅读有关 switch() 控制结构的内容:

PHP: switch - Manual

关于php - 在不使用 eval() 的情况下从数据库记录运行 php 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27316742/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com