Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Jan 2006
    Posts
    377
    Thanks
    8
    Thanked 1 Time in 1 Post

    Keeping PHP code in MySQL DB

    Hello,

    I would like to enter PHP code in a textarea and keep it in a DB field. When the time comes I would like to be able to call the code from the DB and use it (execute or include it). Is this possible?

  • #2
    Regular Coder
    Join Date
    Apr 2003
    Location
    Montreal, QC
    Posts
    340
    Thanks
    3
    Thanked 2 Times in 2 Posts
    Hi,

    Yes, this should be possible.

    When you store the data in the DB you'll need to escape it so that any queries or special characters in your code won't be executed by the DB server. If you're using MySQL try this function that I found on either php.net or mysql.com, (I can't remember which):
    PHP Code:
    function quote_safe($value)
    {
       
    // Stripslashes
       
    if (get_magic_quotes_gpc()) {
           
    $value stripslashes($value);
       }
       
    // Quote if not a number or a numeric string
       
    if (!is_numeric($value)) {
           
    $value "'" mysql_real_escape_string($value) . "'";
       }
       return 
    $value;

    It adds quotation marks to text automatically so you don't have to, and renders your data safe for a mysql query. If you're not using MySQL addslashes() may suffice, but check your DB's documentation to be safe.


    When you bring the data out of the database you shouldn't need to stripslashes or anything. Just load the code into a string variable, and run eval() on it.

    Example:
    PHP Code:
    eval($code_to_be_executed); 
    That's it!
    Search for Laughter or Just Search?
    GiggleSearch.org
    Blog: www.johnbeales.com
    All About Ballet: www.the-ballet.com

  • #3
    Senior Coder
    Join Date
    Jan 2007
    Posts
    1,648
    Thanks
    1
    Thanked 58 Times in 54 Posts
    Just remember that you are adding a large security risk whenever you use eval().

    I would consider alternatives to storing PHP in a database (there shouldn't be a need for it).


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •