MitMaro
MitMaro

Reputation: 5917

Dynamically Calling PHP Class Methods

Is there any security problem with dynamically calling a method in a class from user input. For example:

<?php
    class A {
        public function foo() {
            return true;
        }
    }

    $obj = new A();

    $method = $_GET['method'];

    $obj->$method();

I am aware that the user will be able to call any method within A, and I am fine with that. I am just curious if there may be other possible security issues.

Upvotes: 2

Views: 165

Answers (2)

Adam Pointer
Adam Pointer

Reputation: 1492

Yes its probably a bad idea, maybe you should restrict allowed methods. Maybe define allowed methods in an array then throw an exception if $method is not in this whitelist.

Also you will need to use the magic __call($name, $args) method to allow these user defined methods to be called.

Upvotes: 1

Pascal MARTIN
Pascal MARTIN

Reputation: 401002

Your user will be able to try calling any possible method from your class -- even try to call non-existant methods (and get a Fatal Error).
If you're fine with this... well, I suppose this is OK.

It doesn't look nice, but I don't think one could inject any other kind of code.


Still, I would at least check if the method exists -- using [**`method_exists()`**][1]

Upvotes: 4

Related Questions