在PHP中使用变量变量是不好的做法? [英] is it bad practice to use variable variables in php in the following fashion?
问题描述
例如,一个简单的mvc类型系统:
For example, a simple mvc type system:
/ api / class / method使用.htaccess / nginx.conf重写为php变量
/api/class/method rewritten into php variables using .htaccess/nginx.conf
然后执行类似的操作:
<?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 基本上,我使用变量变量的原因是以使其简单的扩展核心系统 - 即 - 添加在一个新的控制器是好的和简单的。我绝对明白允许基本上任何函数或类无需某种过滤器实例化的安全风险。
EDIT Essentially the reason i'm using variable variables is to make it simple to expand the core system - ie - 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屋!