tags:

views:

158

answers:

5

Anybody have any idea how I might go about doing something like this.

I've got a textarea setup to allow users to edit page content. the content is then stored in a database and is retrieved on the frontend by php within an html template. something like:

<html>
yada yada...
<?php
echo get_page_contents_by_id($_GET['id']);
?>
yada yada...
</html>

its all run in a .php file, in case anyone wanted to call that out.

What I'm wondering is, because I'm getting the content from the database via php, is there any way that I can retrieve php code within that content and still run it without doing any sort of file writing.

+3  A: 

You can use the PHP eval() method to execute the PHP code returned from the database - just as if it was actually written in your PHP file directly.

e.g.

<?php
eval("echo('hello world');");
?>

Prints:

hello world

James
thanks! I totally forgot this existed.
seventeen
yeah it's awesome for when you want to create security holes in your products that actually make it convenient to compromise your site.
iddqd
I would hope that the person who has access to entering the PHP code would be a trusted user, still it's not a great idea I agree. Better to just give the user a WYSIWYG editor or some kind of basic templating language.
James
actually i've come up with a better way to do it. more code. but much safer. because there are only a few methods (that i have defined) i would ever like to be called. I am stripping out the method calls from the string, then using call_user_func() to make sure that the method being called actually exists.
seventeen
This might be a good place to implement a small template system that works only on a defined set of functions.
Pekka
eval()? moar like evil().
Andrew
+1  A: 

You can use eval for this purpose.

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

Gazler
+1  A: 

eval() is as James Goodwin and Gazler say in fact the only way to execute PHP code from string data.

In addition to the security consequences - it will become possible to compromise your whole web site by gaining access to your mySQL data - this approach will make code very hard to debug, as you will have to follow all error messages through the eval()d code.

Pekka
As soon as I saw eval() everything everyone ever told me about it came back. I will think of a more secure way to execute what I'm trying to do. Thanks!
seventeen
A: 

I attempted to do this same thing, but with the addition of tags and normal HTML tags. This will not work. If you need to store HTML along with your PHP, consider a more XHR solution that relies less on PHP code for every page.

Carlson Technology
A: 

Consider another alternative. Really.

Regardless of any security checks you do, function parsing, etc., this is still an EXTREMELY bad idea.

A slightly less bad idea, why not look into a templating solution like http://www.smarty.net or http://www.google.com/search?q=php+template+engine

Eli