M
M
mihelsonkk2015-12-03 00:20:46
PHP
mihelsonkk, 2015-12-03 00:20:46

Php - Storing formulas in the database - eval or are there options?

The table stores pieces of php code, in fact it is a formula for calculating one resulting value.
Now it is implemented like this - the input parameters for the formula are determined, then the php file is included (cache from the database) - after the inclusion, the variable ($res, the same scheme in all formulas) is simply used further. That is a black box.
The formulas are not tricky - there are if - elseif -else branches, assignments, comparisons and round
UPD Syntax is very simple. Example.

$summa = 0;

$sf = $n_square / $n_floor; 
if ($n_square > 30) {$f_square = $n_square;} else {$f_square = 30;} 


$f_electr =226;
$f_otopl =164;
$f_vodkan =108;

  if ($n_water) $summa += 5000 + $n_square*$f_vodkan;
  if ($n_heat) $summa += 5000 + $n_square*$f_otopl;
  if ($n_elec) $summa += 5000 + $n_square*$f_electr;

  if ($n_wall == 1)
  {
    if ($n_wall_diameter == 1) {if ($n_floor == 2) $summa +=($f_brevno200-$f_forsten)*$f_square; else $summa +=($f_brevno200 - $f_forsten)*1.66 *$f_square;}

    elseif ($n_wall_diameter == 3) {if ($n_floor == 2) $summa +=($f_brevno280-$f_forsten)*$f_square; else $summa +=($f_brevno280 - $f_forsten)*1.66 *$f_square;}
  }

  elseif ($n_wall == 2)
  {
    if ($n_wall_section == 1) {if ($n_floor == 2) $summa +=($f_brus160-$f_forsten)*$f_square; else $summa +=($f_brus160 - $f_forsten)*1.66 *$f_square;}
    elseif ($n_wall_section == 2) {if ($n_floor == 2) $summa +=($f_brus200-$f_forsten)*$f_square; else $summa +=($f_brus200 - $f_forsten)*1.66 *$f_square;}

  }

  elseif ($n_wall == 3) {if ($n_floor == 2) $summa +=($f_karkas-$f_forsten)*$f_square; else $summa +=($f_karkas - $f_forsten)*1.66 *$f_square;}

  elseif ($n_wall == 4) {if ($n_floor == 2) $summa +=($f_fahverk-$f_forsten)*$f_square; else $summa +=($f_fahverk - $f_forsten)*1.66 *$f_square;}
$summa = round($summa,-3);

I am rewriting the whole project and now I have reached this point. For obvious reasons, I don’t want to leave it as it is, but the formulas need to be defined in the database.
The first thought is to change cache+include to eval, wrapping it in try except, but this will not help much in terms of security. It is not only the execution of arbitrary code that worries me, but also possible errors in the code from the database.
What do you advise?
Is there any simple math-logic analyzer for php - feed it a formula as a string and get a value at the output?
If all the same eval - then how to make it safer?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Burov, 2015-12-03
@BuriK666

php.net/manual/en/book.lua.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question