function - PHP - eval code from DB -
there have been hundreds if not thousands of posts concerning use of php's eval(); run code database. through searching have not found answer question (explained shortly).
firstly i'll introduce application.
i have 3 records of valid code stored in database:
eg:
['code1']
$num1 = 1; $num2 = 3; $num3 = $num1+$num2; //4
['code2']
$num4 = $num3; //4 $num5 = 5; $num6 = $num4+$num5; //9
['code3']
$num7 = $num4; //4 $num8 = $num6; //9 $num9 = $num7+$num8; //13 echo $num9; //13
next have function call , run record:
eg:
function runcode($codename) { // assume db connection established $result = mysql_query("select `code` codestore `name` = '".$codename."'"); if ($result) { // fetch 1 row $row = mysql_fetch_assoc($result); if (!$row) { die('no rows returned.'); } else { return eval($row['code']); } } else { die('invalid query: '.mysql_error()); } }
now, needs happen call 3 above snippets, 1 after each other, , have variables inside ($numx) available use between each other.
eg:
runcode('code1'); runcode('code2'); runcode('code3');
the above call of 3 snippets db should echo '13', not. , there question:
how can make these variables available outside eval'd code?
variables db local in function. make them global.
so may use global keyword change variables scope:
<?php error_reporting (e_all); $txt = array( '$num1 = 1; $num2 = 3; global $num3; // make global, used later $num3 = $num1+$num2; echo "num3=" . $num3 . "<br>"; //4', 'global $num3; // need use value var global $num4; // make global, used later $num4 = $num3; //4 $num5 = 5; global $num6; // make global, used later $num6 = $num3+$num5; echo "num6=" . $num6 . "<br>"; //9', 'global $num4; // need use value var global $num6; // need use value var $num7 = $num4; //4 $num8 = $num6; //9 global $num9; // make global, used later (maybe) $num9 = $num7+$num8; //13 echo "num9=" . $num9 . "<br>"; //13' ); function runcode($codename) { // example eval($codename); } runcode($txt[0]); runcode($txt[1]); runcode($txt[2]); ?>
this solution demands changing existing code in db. may difficult.
so, here different algorithm. @ first, join code chunks together. run eval function , pass joined code it. example:
function composecode($codename) { // assume db connection established $result = mysql_query("select `code` codestore `name` = '".$codename."'"); if ($result) { // fetch 1 row $row = mysql_fetch_assoc($result); if (!$row) { die('no rows returned.'); } else { return $row['code']; // changed original code } } else { die('invalid query: '.mysql_error()); } } $code = ''; $code .= composecode('code1'); $code .= composecode('code2'); $code .= composecode('code3'); eval($code);
Comments
Post a Comment