I would like to know how to run the php scripts which are stored in the database without using eval().
The expected process is as follow
When user POST a string which contains
{{typed_alias}}, the system will search the table whether this alias has record in thealiascolumn.If yes -> replace what user typed with the correspond script which is stored in the
replacementcolumn.If not -> show the original string including
{{wrong_alias}}
The expected result is as follow
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()+86400Return
Hello, {{morninggg}}, the current unix time is 147855220
Now I have already solved the database array by using foreach and also can replace the alias with script by using str_replace().
Current classI use to foreach data from database and do the replacement is as follow
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;
}
}
Current using method
$replace = new replace();
$replace->setDefinitions($tagEngine);
$parsedString = $replace->tag($__input);
//$__input is what user POST to the server
echo $parsedString;
However, the current result is as follow
Hello, {{morninggg}}, the current unix time is time()
The script can't be run successfully on the page
But when I give the definition manually like this
$definition = array('morning' => 'Good Morning', 'nowTime' => time()); foreach ($definition as $key => $value) $source = str_replace('{{' . $key . '}}', $value, $source); return $source;
The script can be run and returns
Hello, {{morninggg}}, the current unix time is 147855220
I know that using eval() can run the scripts, however, it is regarded as a dangerous method in a real-world application by people.
Can anyone give me suggestions about how to deal with this problem?
Thank you!
eval(), except not storing PHP code in your database. Which is exactly what you should do.time()when I give the definition manually.