如果不在路由中,CodeIgniter会禁用URL

问题描述 投票:1回答:2

这是我的文件夹结构。

|--Application
|-----Controllers
|--------Dashboard.php
|--------Projects.php
|-----Models
|--------dashboardModel.php
|--------projectsModel.php
|-----Views
|--------dashboard (folder)
|-----------index.php
|-----------projects (folder)
|--------------add.php
|--------------index.php

现在,在我的路径文件中,我有以下内容:

$route['default_controller']  = "dashboard";

$route['dashboard/projects']        = "projects";
$route['dashboard/projects/add']    = "projects/add";

现在的问题是:如果我输入网址http://myproject/dashboard/projects它的工作原理如果我输入http://myproject/projects它也有效..如何拒绝第二个网址?

php codeigniter codeigniter-url
2个回答
1
投票

Codeigniter URL映射/路由适用于以下过程:

  • 路由数组中是否存在与URI的完全匹配?
  • 路由数组中是否存在与请求匹配的正则表达式?
  • 尝试使用map路由到匹配请求的控制器:“controller [/ method [/ params]]”

因此,没有设置可以切换到停止路由到最后一个...

您必须使用自定义方式扩展路由器,如下所示:

application/core/中创建一个名为MY_Router.php的文件,它将容纳你的自定义路由器,它看起来像这样:

class My_Router extends CI_Router {
    function _parse_routes()
    {
        // Turn the segment array into a URI string
        $uri = implode('/', $this->uri->segments);

        // Is there a literal match?  If so we're done
        if (isset($this->routes[$uri]))
        {
            return $this->_set_request(explode('/', $this->routes[$uri]));
        }

        // Loop through the route array looking for wild-cards
        foreach ($this->routes as $key => $val)
        {
            // Convert wild-cards to RegEx
            $key = str_replace(':any', '.+', str_replace(':num', '[0-9]+', $key));

            // Does the RegEx match?
            if (preg_match('#^'.$key.'$#', $uri))
            {
                // Do we have a back-reference?
                if (strpos($val, '$') !== FALSE AND strpos($key, '(') !== FALSE)
                {
                    $val = preg_replace('#^'.$key.'$#', $val, $uri);
                }

                return $this->_set_request(explode('/', $val));
            }
        }

        // INSTEAD show 404..
        if (count($this->uri->segments) !== 0) {
            show_404();
        }
        else {
            // If we got this far it means we didn't encounter a
            // matching route so we'll set the site default route
            $this->_set_request($this->uri->segments);
        }
    }
}

你的类的名称取决于subclass_prefix配置变量设置的内容(默认情况下它的MY_但你可能已经改变了它...


2
投票

我知道这已经过了一年,但是想发布给其他寻找更简单选择的人。

您总是可以在config / routes.php的底部放置这些内容。它将捕获过滤器未拾取的任何路由,并将它们发送到您指定的位置。 / auth / invalid生成标准错误消息并将其返回。

这允许我将URL列入白名单,因此用户无法以我可能不计划的方式访问控制器。

$route['(:any)/(:any)/(:any)/(:any)'] = '/auth/invalid';
$route['(:any)/(:any)/(:any)'] = '/auth/invalid';
$route['(:any)/(:any)'] = '/auth/invalid';
$route['(:any)'] = '/auth/invalid';
© www.soinside.com 2019 - 2024. All rights reserved.