php - 如何为 php mvc 构建一个好的路由器

标签 php model-view-controller

我正在尝试使用 php mvc,但遇到了以下问题。我的请求和路由器类非常简单,我想扩展主题以处理来自子文件夹的 Controller 调用,并且 Controller 类函数应该能够获取 url 变量,将其发送给 get 和 post。

我的路由器看起来是这样的

class Router{

    public static function route(Request $request){


        $controller = $request->getController().'Controller';

        $method = $request->getMethod();

        $args = $request->getArgs();


        $controllerFile = __SITE_PATH.'/controllers/'.$controller.'.php';


        if(is_readable($controllerFile)){
            require_once $controllerFile;

            $controller = new $controller;


            if(!empty($args)){
                call_user_func_array(array($controller,$method),$args);
            }else{  
                call_user_func(array($controller,$method));
            }   
            return;
        }

        throw new Exception('404 - '.$request->getController().'--Controller not found');
    }
}

和请求类

    private $_controller;


    private $_method;

    private $_args;

    public function __construct(){

        $parts = explode('/',$_SERVER['REQUEST_URI']);


        $this->_controller = ($c = array_shift($parts))? $c: 'index';
        $this->_method = ($c = array_shift($parts))? $c: 'index';

        $this->_args = (isset($parts[0])) ? $parts : array();

    }

    public function getController(){

        return $this->_controller;

    }
    public function getMethod(){

        return $this->_method;

    }
    public function getArgs(){

        return $this->_args;
    }
}

问题是:当我尝试将抛出的 ajax 变量发送到 Controller 方法时,由于其 url 结构,该方法无法识别。 例如

index/ajax?mod_title=shop+marks&domain=example

只要看起来就被接受

index/ajax/shop+mark/example

最佳答案

您的代码包含所谓的 LFI vulnerability并且在当前状态下是危险的。
您应该将可以用作 $controller 的内容列入白名单,否则攻击者可能会尝试使用 NUL 字节来指定某些内容,并可能上升到一个目录以包含不应包含的文件,例如/etc/passwd,配置文件等等。

您的路由器使用不安全;当心!

编辑:白名单示例

$safe = array(
    'ajax',
    'somecontroller',
    'foo',
    'bar',
);
if(!in_array($this->_controller, $safe))
{
    throw new Exception(); // replace me with your own error 404 stuff
}

关于php - 如何为 php mvc 构建一个好的路由器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10734741/

相关文章:

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

php - 将包含数据的新行添加到 ACF 中的现有转发器

spring.view.prefix : not being applied to simple view name in Spring Boot

c# - 在 MVC 中将数据从 View 传递到部分 View

PHP 对数组的数组进行排序

php - fatal error : Uncaught Error: Call to undefined function is_product()

php - 使用交叉表时如何在 Postgresql 中准备语句

java - 在MVC架构中, `View`可以访问模型吗?

javascript - 在开始 Ember.js 时,Rails 或服务器端开发人员应该进行哪些思维范式转变?

php - AJAX 和 MVC 模式