dongniechi7825 2017-08-19 18:37
浏览 101
已采纳

使用eval() - 函数检查变量

I have a list of variables (var1, var2, ...). Now I'd like to check these variables using several conditions and print out an error message if the condition is true.

As there are many "checks" that should be done I saved the "conditions" in a MySQL-DB (varchar):

condition               errormsg
--------------------------------------------------------
$var1!=1 && $var1!=2    var1 should be 1 or 2
$var1==''               var1 is missing
$var3<0 & $var3>10      var3 should be between 0 and 10

Now I'd like to check these variables using the eval-Function:

$res=mysqli_query($con, "SELECT * FROM conditions");

while($row=mysqli_fetch_object($res)){
 if(eval($row->condition))
  echo $row->errormsg;
}

Can this work or is there a better solution without eval()? Thank you for your help!

  • 写回答

3条回答 默认 最新

  • dongyanghan0556 2017-08-19 19:12
    关注

    Many people suggest to get alternate of this . But if you really need this you can do this way. I don't have your data so I have made this with my own way

     <?php
        $condition = "1!=1";
        //$condition = "1==1";
       $error = "test";
       eval("\$con = $condition ;");
       if($con){
       echo $error;
       }else {
      echo "not found";
      }
    ?>
    

    Uncomment second line to get another change. Just keep in mind that statement should be complete in eval function.

    Live demo : https://eval.in/847626

    Pay special attention not to pass any user provided data into it without properly validating it beforehand.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?