0

I'm using PHP-Parser to build the AST. Then I want to reach the index of Global variables such as $_POST['firstname'] , so I want to reach the index firstname and get it. How to reach the index of global variables, for example;

test

<?php 

$nameValue = $_POST['firstname'];
?>

AST Result:

array( 0: Stmt_Expression( expr: Expr_Assign( var: Expr_Variable( name: nameValue ) expr: Expr_ArrayDimFetch( var: Expr_Variable( name: _POST ) dim: Scalar_String( value: firstname ) ) ) ) )

So how to reach the index firstname and store it in variable?

1 Answers1

1

From your previous code in How to use PHP-Parser to get the global variables name and change it and the code I posted as the answer.

Once you have identified that the node your looking at is a type ArrayDimFetch, and the variable name is of interest (such as _POST in this code), then you can output the dim node (the dimension I assume) value...

$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'
            ) {
                echo $node->dim->value;
            }
    }

});

Update:

After a bit more investigation, the above is fairly strict in that it assumes the index is a literal. To make this more flexible, you can use the functionality in the pretty printer which allows the output of a node instead. So the

echo $node->dim->value;

could be replaced by

$prettyPrinter = new PhpParser\PrettyPrinter\Standard;
echo $prettyPrinter->prettyPrintExpr($node->dim);

So if your code had $_POST['a'."b"] in it, this would correctly output 'a' . "b"/

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55