如何 eval() 字符串的一段
我有一个包含 HTML & 的字符串 PHP中,当我从数据库中提取字符串时,它会回显到屏幕上,但PHP代码不显示。 该字符串如下所示:
$string = 'Hello <?php echo 'World';?>';
echo $string;
输出
Hello
源代码
Hello <?php echo 'World';?>
当我查看源代码时,我可以看到那里的 php 行。 所以我需要做的是 eval() 只是字符串中的 php 段。
需要考虑的一件事是,PHP 在任何给定时间都可能位于字符串中的任何位置。
* 只是为了澄清一下,我的 PHP 配置是正确的,这是一些 PHP 从数据库中转储而不渲染的情况,因为我正在回显包含 PHP 代码的变量,它无法运行。 *
再次感谢我可能收到的任何帮助。
I have a string that has HTML & PHP in it, when I pull the string from the database, it is echo'd to screen, but the PHP code doesn't display. The string looks like this:
$string = 'Hello <?php echo 'World';?>';
echo $string;
Output
Hello
Source Code
Hello <?php echo 'World';?>
When I look in the source code, I can see the php line there. So what I need to do is eval() just the php segment that is in the string.
One thing to consider is that the PHP could be located anywhere in the string at any given time.
* Just to clarify, my PHP config is correct, this is a case of some PHP being dumped from the database and not rendering, because I am echo'ing a variable with the PHP code in it, it fails to run. *
Thanks again for any help I may receive.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这会起作用,但就像其他人已经和将要建议的那样,这是一个糟糕的主意。 您的应用程序架构永远不应该围绕在数据库中存储代码而展开。
最简单的是,如果您的页面始终需要显示字符串,请将这些字符串存储在数据库中,而不是生成它们的代码。 现实世界的数据比这更复杂,但必须始终在数据库中正确建模。
编辑:需要使用 preg_replace_callback 进行调整才能正确删除源/插值。
This will work, but like others have and will suggest, this is a terrible idea. Your application architecture should never revolve around storing code in the database.
Most simply, if you have pages that always need to display strings, store those strings in the database, not code to produce them. Real world data is more complicated than this, but must always be properly modelled in the database.
Edit: Would need adapting with preg_replace_callback to remove the source/interpolate correctly.
您不应该评估 php 代码,只需运行它即可。 需要安装 php 解释器,并正确配置 apache+php。 那么这个 .php 文件应该输出 Hello World。
编辑答案:
使用 preg_replace_callback 获取 php 部分,对其进行评估,将输入替换为输出,然后回显它。
但。 如果你应该评估来自数据库的东西,我几乎可以肯定,这是一个设计错误。
You shouldn't eval the php code, just run it. It's need to be php interpreter installed, and apache+php properly configured. Then this .php file should output Hello World.
Answer to the edit:
Use preg_replace_callback to get the php part, eval it, replace the input to the output, then echo it.
But. If you should eval things come from database, i'm almost sure, it's a design error.
只要代码是正确的 PHP 并且以分号结尾,eval() 就应该可以正常工作。 首先去掉 php 标签,然后评估它怎么样?
以下示例经过测试并且有效:
只需确保您从数据库检索的任何内容都已首先正确清理,因为您实际上允许任何可以将内容获取到数据库的人执行代码。
eval() should work fine, as long as the code is proper PHP and ends with a semicolon. How about you strip off the php tag first, then eval it.
The following example was tested and works:
Just make sure that whatever you retrieve from the db has been properly sanitized first, since you're essentially allowing anyone who can get content into the db, to execute code.