phpcodeignitercodeigniter-url

CodeIgniter disallow URL if not in route


This is my folder structure.

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

Now, in my route file I have the following:

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

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

Now the problem: if I type in the url http://myproject/dashboard/projects it works AND if I type http://myproject/projects it also works..how do I deny the second url?


Solution

  • Codeigniter URL mapping / routing works on the following process:

    So there is no setting to switch to stop it from routing to the last one...

    you must extend the Router with a custom one like so:

    in application/core/ create a file called MY_Router.php this will house your custom router, and it will look something like this:

    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);
            }
        }
    }
    

    the name of your class depends on what the subclass_prefix config variable is set to (by default its MY_ but you may have changed it..