executing code from database

前端 未结 8 465
逝去的感伤
逝去的感伤 2021-01-29 14:42

I have a PHP code stored in the database, I need to execute it when retrieved.

But my code is a mix of HTML and PHP, mainly used in echo \"\";

A sample that look

8条回答
  •  情话喂你
    2021-01-29 15:19

    As everyone'd indicated using eval() is a bad approach for your need. But you can have almost the same result by using whitelist approach.

    • Make a php file , db_driven_functions.php for instance. get your data from db. and map them in an array as below

    //$sql_fn_parameters[0] = function name

    //$sql_fn_parameters[1,2,3.....] = function parameters

    • Then define functions those include your php code blocks.for instance

      my_echo($sql_fn_parameters){
      
           echo $sql_fn_parameters[1];//numbered or assoc..
      
      }
      
    • then pull the data which contains function name

    • after controlling if that function is defined
    function_exists("$sql_fn_parameters[0]")
    

    • call function

      call_user_func_array() or call_user_func()

    ( any you may also filter parameters array $sql_sourced_parameters_array does not contain any risky syntaxes for more security.)

    And have your code controlled from db without a risk.

    seems a little bit long way but after implementing it's really a joy to use an admin panel driven php flow.

    BUT building a structure like this with OOP is better in long term. (Autoloading of classes etc. )

提交回复
热议问题