AAA
AAA

Reputation: 3168

Storing and echoing php code in db

I have been trying to test this out. I put in the code below in the database.

  <?php

   $test = "Whats up";

   print $test;

   ?>

And then on a page i do select and then i try to echo but it won't do it unless i rid the entry of the start and end tags. So if i wanted to execute this php by calling it from the db, how would i do it? Thanks.

Upvotes: 0

Views: 122

Answers (3)

Andi Lee Davis
Andi Lee Davis

Reputation: 85

Hi This is exactly what I was looking for. We have CMS deployed accross multiple servers and in order to maintain the base functions (without the need to make a url based include of our main functions file) it was easier to store and call these functions from our group=wide single database. We use medium blob and store a serialized base_64 encoded text file there.

So to serialize the code we use this script without the php tags:

<form name="serialise_script" action="" method="post" >
    <p>Put Script in here (without php tags???)</p>
    <textarea cols="100" rows="25" name="serializeme" ></textarea>
    <input type="submit" name="go" value="go" />
</form>

<?php if(isset($_POST['serializeme'])){
    echo "<p>Your Code</p><textarea style='border:3px solid black;padding:0.5em;' cols='100' rows='25' >" . base64_encode(serialize($_POST['serializeme'])) . "</textarea>";
 } ?>

Then copy the script and paste the output code into a text file. Upload that to the medium blob table

Then to output again from the database and set to a session variable... I just did this:

eval(unserialize(base64_decode($_SESSION['functions'])));

But it was the eval bit I needed to make it work. By serializing and encoding means we shouldn't have any problems.

Now all I need to do is manage 1 base code for many sites across certain servers. AKA One bug fix would solve all issues across all deployments.

Thanks

Andi

Upvotes: 0

sdemirkeser
sdemirkeser

Reputation: 440

you could use serialize - unserialize function to save object or variable. and you can use eval function to run code

Upvotes: 1

Emil Vikstr&#246;m
Emil Vikstr&#246;m

Reputation: 91942

Use eval to treat a string as runnable PHP code, for example:

<?php
$string = 'echo "hello";';
eval($string);
?>

As Pekka suggests, this is bad practice and you should probably rethink your solution. There's hardly ever motivated to store code in the database (the database is for data).

Upvotes: 1

Related Questions