PHP 评估无法正确执行



有人可以指出我在这里弄错了什么吗? :)

<?php
$q = $_GET[q];
$acuman = <<<PARSE
input: (contains: "hello"){
output: "hello";
}
PARSE;
$acuman = str_replace("input: (contains: ", 'if(strpos(', $acuman);
$acuman = str_replace("){", ', $q) !== false) {', $acuman);
$acuman = str_replace("output: ", '$output = ', $acuman);
eval($acuman);
?>

我正在尝试执行字符串$acuman,一个已被各种str_replace函数更改的heredoc。然而,它not做我想要做的事情,我对该做什么感到困惑,因为我尝试了很多不同的事情。

由于许多人似乎感到困惑:我的目的是将字符串中的代码$acuman作为代码正确执行。我只想让eval函数工作。我知道 eval 是邪恶的,请停下来:我只是在寻求帮助来解决手头的问题。

编辑:当我回显字符串$acuman时,这就是我得到的:

if(strpos("hello", $q) !== false) { $output = "hello"; }

参数顺序错误:

if(strpos($q, "hello") !== false) { $output = "hello"; }

strpos()将"haystack"(正在搜索的字符串(作为第一个参数,将"needle"(在"haystack"中查找的字符串(作为第二个参数。

好的,所以... $acuman似乎包含以下内容:

if(strpos("hello", $q) !== false) {
  echo "hello";
}

这表示$q需要包含一部分"hello"才能回显字符串"hello"

我在这里没有看到任何问题,除了$q = $_GET[q];不适用于任何现代版本,q因为它被视为常量,而不是变量或字符串文字数组索引。请参阅有关此主题的 PHP 文档。

改为$q = $_GET['q'];(注意引号(后,似乎此代码确实有效。每当将"hello"的任何部分传递给 URL 参数(传递给 PHP 代码(时,它都会输出"hello"

不用说:不要将此代码用于生产。代码本身非常容易受到攻击,并允许用户将原始PHP代码传递给您的脚本以执行。这段代码的功能可以以更安全的方式完全重写,但你已经表达了继续使用eval();的愿望,所以请小心。

享受。

相关内容

最新更新