Rob*_*itt 5 php regex methods object
我目前正在为一家公司开发一个MVC Style框架,出于安全考虑,我需要确保通过Query String传递的控制器/方法是RFC的有效字符(我找不到).
我需要能够根据PHP解释器允许的内容来验证/清理类名
例如:
class SomEFunk__YClAssName extends Controller
{
}
Run Code Online (Sandbox Code Playgroud)
我需要某种正则表达式来验证SomEFunk__YClAssName和消毒它,如果需要的话!这也是与方法相同的原则.
有一些事情需要考虑,比如
关于这个或可能表达的任何信息都会非常有用.
这是我的一些路由器代码,因此您可以看到我需要实现它的位置:
private function prepareQueryString()
{
if(strlen($this->query_string) == 0)
{
return;
}
//Remove [ending|starting|multiple] slashes
$this->query_string = preg_replace('/^\/+|\/+$|\/(?=\/)/', '', $this->query_string);
foreach(explode('/',$this->query_string) as $Key => $Value)
{
if($Key == 0)
{
$Controller = $this->AssignController($Value);
}
if($Key == 1)
{
$this->AssignMethod($Value);
}else
{
$this->AssignParam($Value);
}
}
//Build RouterVar stdClass
}
public function AssignController(String $Controller)
{
if(!empty($Controller))
{
//Sanitize
}
}
public function AssignMethod(String $Method)
{
if(!empty($Method))
{
//Sanitize
}
}
public function AssignParam(String $Param)
{
$this->params[] = $Param;
}
Run Code Online (Sandbox Code Playgroud)
您将看到需要检查的评论"Sanitize".
nat*_*ate 18
我相信你正在寻找的正则表达式是:
<?php
preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $input);
?>
Run Code Online (Sandbox Code Playgroud)
根据:http://php.net/manual/en/language.oop5.basic.php
你最好使用一个非常通用的正则表达式,然后通过简单的调用来测试该类是否存在class_exists().
这将匹配任何有效的PHP类名称,包括非常奇怪的类名称,___或者_3两者都是有效的类名:
/^[a-z_]\w+$/i
Run Code Online (Sandbox Code Playgroud)
我个人比PHP的类命名约定更具限制性.我要求我的控制器大写,并进行后期修复,_controller以便不通过奇怪的URL调用奇怪的非控制器类.我会用这样的东西:
class Products_controller extends Controller { }
// elsewhere, after parsing the controller name from the URI:
if (preg_match('/^[A-Z]\w+_controller$/', $controller_name)
&& class_exists($controller_name)) {
$controller = new $controller_name();
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,通过查询字符串传递控制器名称会产生非常丑陋和搜索引擎不友好的URL.考虑在URL中构建控制器名称和方法:
/products/index # controller=products, action=index
/users/show/3 # controller=users, action=show, user id=3
Run Code Online (Sandbox Code Playgroud)