I want some entities to execute extra code (which returns html), stored in their own data, in database. For this I am trying to store a closure in a field of the table, and execute it after retrieving it.
The closure gives me the opportunity to encapsulate the script (in a scope) and execute it whenever I want after obtaining the database.
The problem is that it doesn't work. Error: 'Fatal error: Uncaught Error: Call to undefined function function () {...
.
(Premise: I know that 'serialization of Closure is not allowed')
Example of the closure stored in database:
function() {
return '<h1>Today is '.date('d/m/Y').'</h1>';
};
Retrieve data and execution of the closure:
//example of retrieve
$sql = "SELECT field FROM table";
$q = $link->query($sql);
$row = $q->fetchRow();
//execution, var must be contain the html processed in the closure
$var = $row['field']();
Can anyone help me with the error or give me another idea to build this scenario?
Many thanks.
CodePudding user response:
You need to eval
the php code.
//execution, var must be contain the html processed in the closure
eval('$fn='.$row['field']);
$var = $fn();
Caution The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.
Document: https://www.php.net/manual/en/function.eval.php
CodePudding user response:
Would it be possible to use printf and store the format string in the database? In that case you won't need an (evil) eval
. The format string is printf or sprintf is quite powerful, but cannot solve all cases. But you could write a custom printf like function that could do what you wanted.