在PHP中使用变量变量是不好的做法吗? [英] Is it bad practice to use variable variables in PHP?
问题描述
例如,一个简单的MVC类型系统:
For example, a simple MVC type system:
/api/class/method
重写为PHP变量,然后执行以下操作:
/api/class/method
rewritten into PHP variables using .htaccess/nginx.conf
, then doing something like:
<?php
// Set up class + method variables
$className = some_class_filter($_GET['class']);
$method = some_method_filter($_GET['method']);
// Check if class exists and execute
if(file_exists(BASE . "/controllers/" . $className . ".class.php")) {
require BASE . "/controllers/" . $className . ".class.php";
$$className = new $className();
// Execute the method
$$className->$method();
} else {
// Spit out some error based on the problem
}
?>
这是非常糟糕的做法吗?如果是不好的做法,有人可以确切解释原因吗?如果是这样,是否有更好的方法来做我正在做的事情?
Is this horribly bad practice? If it is bad practice, can someone explain exactly why? And if so, is there a better way to do what I'm doing?
编辑从本质上讲,我使用变量变量的原因是为了简化核心系统的扩展-即-添加新的控制器非常简单.我绝对理解在没有某种过滤器的情况下允许实例化任何函数或类的安全隐患.
EDIT Essentially the reason I'm using variable variables is to make it simple to expand the core system - i.e. - adding in a new controller is nice and simple. I definitely understand the security risks of allowing essentially any function or class to be instantiated without some kind of filter.
"some_filter_here"可能是允许使用的控制器的列表-此处已经提到了一些白名单.
The 'some_filter_here' could be a list of controllers that are allowed - whitelist as some here have mentioned.
推荐答案
是的,这是很糟糕的做法.您是否需要该实例的变量变量?换句话说,您是否需要多个课程和课程?给定请求中实例化的方法?您的URI结构建议不要这样做.如果没有,您可以使用:
Yes, this is rather bad practise. Do you need a variable variable for that instance? In other words, do you need more than one class & method to be instantiated in a given request? Your URI structure suggests not. If not, you could just use:
$object = new $className();
$object->$method();
否则,您可能想要做:
$objects = array();
$objects[$className] = new $className();
$objects[$className]->$method();
这避免了用变量变量污染范围,而变量变量更难跟踪.
This avoids polluting the scope with variable variables, which are harder to track.
就给定目录中类的存在检查而言,这应该是足够的白名单(假定攻击者无法写入该目录).
As far as the existence checks for your class in a given directory, this should be a sufficient whitelist (presuming an attacker cannot write to that directory).
编辑:作为进一步的检查,您可能需要考虑检查 method_exists 调用该方法之前,先在对象上添加代码>
.
EDIT: As a further check, you may want to consider checking method_exists
on the object before calling the method.
这篇关于在PHP中使用变量变量是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!