0

我已经为我的 MVC 编写了一个基本的路由器类,但是我在链接中使用连字符时遇到了麻烦,它为现有链接提供了 403 Forbidden,但是对于不存在的链接,它会正确打印它们并给出 404 错误页面.

我的控制器类的形式为 Link_Here,我将连字符更改为路由器中的下划线。URL 结构是http://example.com/ {$controller}/($action)/($parameters) 问题是控制器部分

这是我的路由器代码:

    <?php

class Router
{
    private $url, $controller, $method, $params;
    private $allowedChars = array('-', '_', '/', '\\', '.');

    public function __construct()
    {
        if(!empty($_GET['page']))
        {
            if(ctype_alnum(str_replace($this->allowedChars, '', $_GET['page'])))
            {
                $this->url = $_GET['page'];
            }
            else
            {
                throw new Exception("Malformed URL");
            }
        }
        else
        {
            $this->url = 'index';
        }

        $this->url = explode('/', $this->url);

        // This is where I change the hyphen to an underscore
        $this->controller = implode('_', array_map('ucfirst', explode('_', str_replace('-', '_', array_shift($this->url)))));
        $this->method = array_shift($this->url);
        $this->params = &$this->url;
    }

    public function commit()
    {
        if(class_exists($this->controller))
        {
            if(method_exists($this->controller, $this->method) && empty($this->params))
            {
                if(empty($this->params))
                {
                    $ctrl = new $this->controller;
                    $ctrl->loadModel($this->controller);
                    $ctrl->{$this->method};
                }
                else
                {
                    $ctrl = new $this->controller;
                    $ctrl->loadModel($this->controller);
                    $ctrl->{$this->method}($this->params);
                }
            }
            else
            {
                $ctrl = new $this->controller;
                $ctrl->loadModel($this->controller . '_Model');
                $ctrl->index();
            }
        }
        else
        {
            $ctrl = new Error;
            $ctrl->loadModel('Error');
            $ctrl->notFound();
        }
    }
}

我的重写规则:

    <IfModule mod_rewrite.c>
    Options +FollowSymlinks
  # Options +SymLinksIfOwnerMatch
    Options -Indexes

    RewriteEngine On
    # RewriteBase /

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?page=$1 [L,QSA]
</IfModule>
4

0 回答 0