开发者

Parse a string to extract function name and parameter for use with `call_user_func()`

How do I execute the transaction(123) function?

The response via API is: transaction(123)

I store this in the $respon开发者_如何学JAVAse varible.

<?php

function transaction($orderid) {
  return  $orderid;
}

//api response
$response = "transaction(123)";

try {
  $orderid = call_user_func($response);
  echo  $orderid;
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

?>


According to the manual page call_user_func() should be called with two parameters in your use case.

$orderid = call_user_func('transaction', 123);

This means you must extract the function and parameter separately from your $response variable:

preg_match('/([\w\_\d]+)\(([\w\W]*)\)/', $response, $matches);

Would result in the $matches array containing the function name at index 1 and the parameter at index 2.

So you would then do:

$orderid = call_user_func($matches[1], $matches[2]);

Obviously you need to be very careful with the values if they are coming from an untrusted source.


The bad way to do it, is to use the eval() function. It's very bad in your use-case because the API may very well return things you don't want to execute.

The good way to do it is to parse your string, validate its contents, and map the call and its arguments accordingly.

You can parse the return string using a regular expression:

preg_match("/^(.+?)\((.*?)\)$/", $answer, $match);
var_dump($match[1]); // method
var_dump(explode(',', $match[2])); // arguments

You must sanitize/validate the above.


Call call_user_func this way:

$orderid = call_user_func('transaction', 123);

Additionally, take a look at http://es.php.net/manual/en/function.call-user-func.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜