我想使用PHP-Parser库来获取全局方法 ( _POST, _GET, _REQUEST
) 以获取 PHP 中的值。我正在使用PHP-Parser,我想检查节点名称是否等于(_POST, _GET, _REQUEST
)。我还是 PHP-Parser 的初学者,不知道如何获取这些全局变量。例如,如果我有以下源代码:
代码:
<?php
$firstname = $_POST['firstname];
到目前为止,我使用的 PHP 解析器如下所示:
<?php
require_once('vendor/autoload.php');
use PhpParser\Error;
use PhpParser\NodeDumper;
use PhpParser\ParserFactory;
$code = <<<'CODE'
<?php
$firstname= $_POST['firstname'];
CODE;
$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
try {
$ast = $parser->parse($code);
} catch (Error $error) {
echo "Parse error: {$error->getMessage()}\n";
return;
}
use PhpParser\{Node, NodeTraverser, NodeVisitorAbstract};
$traverser = new NodeTraverser;
// This code exist in the PHP-Parser documentation
$traverser->addVisitor(new class extends NodeVisitorAbstract {
public function leaveNode(Node $node) {
if ($node instanceof Node\Stmt\Expression
&& $node->expr instanceof Node\Expr\FuncCall
&& $node->expr->name instanceof Node\Name
&& $node->expr->name->toString() === '_POST'
) {
// Change the $_POST['firstname'] and replace it with XXX value
}
}
});
print_r($modifiedStmts = $traverser->traverse($ast) );
实现上述 PHP-Parser AST 后,我得到以下结果:
Array ( [0] => PhpParser\Node\Stmt\Expression Object ( [expr] => PhpParser\Node\Expr\Assign Object ( [var] => PhpParser\Node\Expr\Variable Object ( [name] => firstname [attributes:protected] => Array ( [startLine] => 2 [endLine] => 2 ) ) [expr] => PhpParser\Node\Expr\ArrayDimFetch Object ( [var] => PhpParser\Node\Expr\Variable Object ( [name] => _POST [attributes:protected] => Array ( [startLine] => 2 [endLine] => 2 ) ) [dim] => PhpParser\Node\Scalar\String_ Object ( [value] => firstname [attributes:protected] => Array ( [startLine] => 2 [endLine] => 2 [kind] => 1 ) ) [attributes:protected] => Array ( [startLine] => 2 [endLine] => 2 ) ) [attributes:protected] => Array ( [startLine] => 2 [endLine] => 2 ) ) [attributes:protected] => Array ( [startLine] => 2 [endLine] => 2 ) ) )
- 如何检测测试代码是否有
_POST, _GET, REQUEST
?例如:
// Something like this
if($node->value === '_POST' OR $node->value === '_GET' or $node->value === '_REQUEST')
{
// Do next step to change the global variable to specific text value
}
- 如何更改
$_POST[firstname]
按hello world! or any text
值?例如:之前
$firstname = $_POST['firstname'];
后
$firstname = "hello World!";
谢谢你的帮助