How to use PHP-Parser to get the global variables name and change it

前端 未结 1 1619
醉梦人生
醉梦人生 2021-01-20 03:09

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

相关标签:
1条回答
  • 2021-01-20 03:42

    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!';
    
    0 讨论(0)
提交回复
热议问题