【发布时间】:2023-03-31 04:40:03
【问题描述】:
我在我的 PHP 类中通过 AJAX 调用了以下代码:
PHP:
class Ajax extends Controller {
private $class;
private $method;
private $params;
function __construct()
{
$this->params = $_POST; // Call params
$call = explode('->', $this->params['call']);
$this->class = new $call[0]; // e.g. controller->method
$this->method = $call[1];
array_shift($this->params);
$this->parse();
}
public function index()
{
//Dummy
}
public function parse()
{
$r = '';
$r = call_user_func_array(array($this->class, $this->method), $this->params);
echo $r;
}
}
客户:
function creditCheck2(id)
{
$.post(ROOT + 'Ajax', {call: 'Record->creditState', id: id, enquiryid: enquiryId}, function(data) {
alert(data)
}, 'json')
}
它似乎工作得很好,但它安全吗?还能做得更好吗?
仅供参考,我已经添加了我的代码以及答案建议的更改:
class Call extends Controller {
private $class;
private $method;
private $params;
private $authClasses = array(
'Gallery'
);
function __construct()
{
$this->params = $_POST; // Call params
$call = explode('->', $this->params['call']);
if(!in_array($call[0], $this->authClasses))
{
die();
}
$this->class = new $call[0]; // e.g. controller->method
$this->method = $call[1];
unset($this->params['call']);
$this->parse();
}
public function parse()
{
$r = '';
$param = array();
// Params in any order...
$mRef = new ReflectionMethod($this->class, $this->method);
foreach($mRef->getParameters() as $p) {
$param[$p->name] = $this->params[$p->name];
}
$this->params = $param;
if($r = @call_user_func_array(array($this->class, $this->method), $this->params))
{
echo $r;
}
else {
}
}
}
【问题讨论】:
-
我个人使用 __call 魔术方法并保护该方法,从而消除任何意外错误。此外,根据您的方法执行的逻辑,您可能希望向参数添加某种过滤器。
-
@IanBrindley 过滤器是指传递另一个定义其他参数是什么数据类型的参数吗?例如...id:id,enquiryid:enquiryId,过滤器:'numeric'...
-
@imperium2335,我已经更新了反射样本。所有功劳归功于 Jon 指出的参考。
标签: php javascript ajax oop code-injection