我不知何故无法理解这行代码的作用:eval("\$s-6ren">
gpt4 book ai didi

php - 请解释这是做什么的 : eval ("\$str =\"$str\";")

转载 作者:行者123 更新时间:2023-12-02 04:44:10 28 4
gpt4 key购买 nike

这段代码来自 php.net 的 eval 手册:

<?php

$string = 'cup';
$name = 'coffee';

$str = 'This is a $string with my $name in it.';
echo $str. "<br>";

eval("\$str = \"$str\";");
echo $str. "<br>";

?>

我不知何故无法理解这行代码的作用:eval("\$str =\"$str\";")

我猜最终效果是这样的:$str = "$str"; 但是当我用它代替 eval 代码时,我没有得到相同的效果。有人可以引导我完成这行代码吗?我知道该功能带来的漏洞。但我的兴趣点仅限于理解特定的代码行。

我想我现在有了答案 -

eval("\$str =\"$str\";")$str = "$str"; 不是一回事。在第二种情况下,$str 被评估为 This is a $string with my $name in it. 在第一种情况下,相同的字符串,因为它仍在 eval 结构中,因此被进一步评估并生成 This is a cup with my coffee in it.

最佳答案

eval()将执行它获取的字符串,就好像它是 PHP 代码一样。

$string = 'cup';
$name = 'coffee';

这几乎是不言自明的。两个值存储在两个变量中,$string$name

$str = 'This is a $string with my $name in it.';
echo $str. "<br>";

这将输出:

This is a $string with my $name in it.

请注意变量没有展开。当变量在单引号内使用时,它们不会被插入——因此结果符合预期。这记录在案 here .

eval("\$str = \"$str\";"); 
echo $str. "<br>";

这可能会让您感到困惑。让我们详细检查一下。在 eval() 语句中,您有以下内容:

"\$str = \"$str\";"
  • \$str - 变量用 \ 转义以避免它被解释为字符串。如果从开头删除反斜杠,PHP 将抛出解析错误。
  • \"$str\"; -- 这里使用变量的实际值,反斜杠用于转义双引号。

运行时,要执行的 PHP 代码如下所示:

$str = "This is a $string with my $name in it.";

最后,您只是像往常一样回显变量,它只会输出:

This is a cup with my coffee in it.

eval() 函数与其他任何函数一样,如果使用不当可能会非常危险。手册警告您:

The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

关于php - 请解释这是做什么的 : eval ("\$str =\"$str\";"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20162385/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com