开发者

How to inject php code from database into php script?

I want to store php code inside my database and then use it into my script.

class A {
    public function getName() {
        return "lux";
    }
}
// instantiates a new A
$a = new A();

Inside my d开发者_如何学Catabase there is data like

"hello {$a->getName()}, how are you ?"

In my php code I load the data into a variable $string

$string = load_data_from_db();
echo $string; // echoes hello {$a->getName()}, how are you ?

So now $string contains "hello {$a->getName()}, how are you ?"

{$a->getName()} still being un-interpretated

Question: I can't find how to write the rest of the code so that {$a->getName()} gets interpretated "into hello lux, how are you". Can someone help ?

$new_string = ??????
echo $new_string; //echoes hello lux, how are you ?

Is there a solution with eval() ? (please no debate about evil eval ;)) Or any other solution ?


take a look at eval() - this is what you are looking for (but i agree with phill, this sounds like bad practice)

EDIT: just seen that you know eval - so why don't you do this:

eval('$string = "'.load_data_from_db().'";');

(haven't tested this, but i'm almost sure it works)


Seems like you are trying to do something like multilanguage strings.

There is a one nifty approach using sprintf

Inside DB you put

"hello %s, how are you ?"

and in your php code you do

$string = load_data_from_db();
echo sprintf($string,$a->getName()); // replaces %s with the function value.

the changing part ($a->getName()) should come from database too but with separate query (maybe in class A)


you could save it to a temporary file like temp.file and then do an include('temp.file');


A database is used to store data NOT code. You should make your code dynamic to read data from the database/user input but storing code in a database is not recommended.

Why not store the value "lux" in a database table.

Try it this way:

class A {
    private $name;

    public function getName() {
        return $this->name;
    }

    public function setName($name) {
        $this->name = $name;
    }
}
// Query DB
// Don't know your query so just using what you have
$passed_name = load_data_from_db(); // This would return "lux"

// instantiates a new A
$a = new A();
$a->setName($passed_name);
echo "hello ".$a->getName().", how are you ?<br />\n";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜