26
$\begingroup$

Currently my code looks like that:

switch ($_POST['operation']) {
    case 'create':
        $db_manager->create();
        break;
    case 'retrieve':
        $db_manager->retrieve();
        break;
...
}

What I want to do is, to check if method called $_POST['operation'] exists: if yes then call it, else echo "error" Is it possible? How can I do this?

$\endgroup$

4 Answers 4

47
$\begingroup$

You can use method_exists:

if (method_exists($db_manager, $_POST['operation'])){
  $db_manager->{$_POST['operation']}();
} else {
  echo 'error';
}

Though I strongly advise you don't go about programming this way...

$\endgroup$
Sign up to request clarification or add additional context in comments.

9 Comments

@epic_syntax: Because I could, with wget/cURL, spoof the POST variable and pry around for methods you don't necessarily want exposed. Also, you NEVER trust user input directly, you always want to sanitize it. basically, if you're using $_POST[...] anywhere else but the top of your file embedded in a check for safe-ness, you're doing it wrong and asking for trouble.
And I almost though, you'd recomend not to use PHP at all :)
@epic_syntax: the easy way is to have whitelist of methods allowed to run
@iblue: you just wanted to share that link and could find better place, didn't you?
@BradChristie There is any safer alternative for method_exists? Could you give a explanation about why you don't recommend using it?
|
13
$\begingroup$

You can use is_callable() or method_exists().

The difference between them is that the latter wouldn't work for the case, if __call() handles the method call.

$\endgroup$

Comments

6
$\begingroup$

Use method_exists()

method_exists($obj, $method_name);
$\endgroup$

Comments

4
$\begingroup$

You can use method_exists(). But this is a really bad idea

If $_POST['operation'] is set to some magic function names (like __set()), your code will still explode. Better use an array of allowed function names.

$\endgroup$

2 Comments

I think, You mean something like this. $operations=array("retrieve", "create"); if (isset($_POST['operation']) && in_array($_POST['operation'], $operations)) { $db_manager->{$_POST['operation']}(); } Can I collect all available methods into an array automatically or only manually?
Letting users call arbitrary methods in an object is generally a bad idea (and its slow as hell). Make your own list, or even better use the switch statement from your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.