executing code from database

前端 未结 8 461
逝去的感伤
逝去的感伤 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:08

    use the eval() function.

    heres some info

    http://www.php.net/manual/en/function.eval.php

    something along the lines of:

    eval($yourcode);
    

    If that is the last resort, you want it to be secure as it will evaluate anything and hackers love that. Look into Suhosin or other paths to secure this in production.

    0 讨论(0)
  • 2021-01-29 15:11

    Eval is not safe obviously.

    The best route IMO

    1. Save your data in a table

    2. Run a stored procedure when you are ready to grab and process that data

    0 讨论(0)
  • 2021-01-29 15:11

    You should not abuse the database this way. And in general, dynamic code execution is a bad idea. You could employ a more elegant solution to this problem using template engines like Smarty or XSLT.

    0 讨论(0)
  • 2021-01-29 15:14

    It's not only a bad idea but also invitation to several type of hacking attempts.

    You can do with eval(). but never use it . The eval() 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.

    0 讨论(0)
  • 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. )

    0 讨论(0)
  • 2021-01-29 15:21

    I have a PHP code stored in the database

    STOP now.
    Move the code out of the database.
    And never mix your code with data again.

    0 讨论(0)
提交回复
热议问题