且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在数据库中保存php代码

更新时间:2022-10-25 08:41:38

如果您真的想这样做,可以使用 eval()作为您的方法c)建议:

  $ var //您的变量与DB中的数据
<?php echo eval(?>。$ var。&lt ;?)?

有许多合法的使用情况,你想在数据库中存储PHP命令,我个人觉得大喊不要做,而不知道情况有点无益。



无论如何,正如在各种线程中已经指出的,有安全问题和其他陷阱使用这种方法,我会建议反对它。它会使调试更困难,并增加潜在的安全漏洞,等等...



阅读 this post and 的帖子,以了解更多关于使用eval()的陷阱。


Currently I am working on a project in which I have to save some PHP code in database, I am saving the code with PHP tags.

But I am not getting how I can retrieve the code exactly as stored into database.

I have tried the following methods :

a) Direct retrieval : When I am retrieving the databse directly then the value of $row['code'] is blank

b) using eval() : When I am using eval() then I am getting syntax error :

syntax error, unexpected '<' in H:\xampp\htdocs\trycodeonline\testing.php(27) : eval()'d code on line 1

c) using eval() without php tags : when I am removing the php codes then I am getting result instead of code, like I want to print echo "hello" but it is printing "hello"

So how can I print the php code ?

If you really want to do it, you can use eval() as your method c) suggests:

$var // your variable with the data from the DB
<?php echo eval("?>". $var ."<?") ?>

There are many legitimate use-cases where you'll want to store PHP commands in a database, and I personally find shouting "dont do it" without knowing the circumstances a bit unhelpful.

Anyway, as has already been pointed out in various threads, there are security issues and other pitfalls using this approach and I would recommend against it. It will make debugging harder, and increases potential security vulnerabilities, and so on...

Read this post and this post to know more about the pitfalls of using eval().