I want to use PHP-Parser library to get the global method (_POST, _GET, _REQUEST
) to get values in PHP. I\'m using PHP-Parser where I want to check the node nam
This should work for the particular instance you have highlighted, it only does the POST instance, but that should be easy to expand.
The main part is when you see the AST for the code, try and make sure you can identify the base of the _POST
access. This turns out to be a Node\Expr\ArrayDimFetch
, then inside this you want to check if the variable it is using is _POST
.
Once you have identified this, you can replace that node with a new one which is just a string Node\Scalar\String_("Hello World!");
.
$traverser->addVisitor(new class extends NodeVisitorAbstract {
public function leaveNode(Node $node) {
if ($node instanceof Node\Expr\ArrayDimFetch
&& $node->var instanceof Node\Expr\Variable
&& $node->var->name === '_POST'
) {
// Change the $_POST['firstname'] and replace it with XXX value
return new Node\Scalar\String_("Hello World!");
}
}
});
$prettyPrinter = new PhpParser\PrettyPrinter\Standard;
echo $prettyPrinter->prettyPrintFile($traverser->traverse($ast));
From your original code of
<?php
$firstname= $_POST['firstname'];
this code outputs....
<?php
$firstname = 'Hello World!';