Case Insensitive Routing in CodeIgniter

2019-02-18 11:39发布

问题:

I've written this in the CodeIgniter's routers.

$route['companyname'] = "/profile/1";

This is working fine but when I type "CompanyName" into the URL then it doesn't work. This is because upper case characters.

I want to make this routing case insensitive. Please suggest the best way.

回答1:

Just add expression "(?i)"
Here example:
$route['(?i)companyname'] = "/profile/1";



回答2:

If you want case-insensitive routing for all routes, you just need to extend CI_Router class, then modify _parse_routes() method like this:

public function _parse_routes()
{
    foreach ($this->uri->segments as &$segment)
    {
        $segment = strtolower($segment);
    }

    return parent::_parse_routes();
}

It will be cleaner than editing the CI_URI class itself. :)



回答3:

Use hooks:

Create application/hooks/LowerUrl.php

class LowerUrl {
    public function run() {
            $_SERVER['REQUEST_URI'] = strtolower($_SERVER['REQUEST_URI']);
    }
}

Add to application/config/hooks.php

$hook['pre_system'] = array(
    'class'    => 'LowerUrl',
    'function' => 'run',
    'filename' => 'LowerUrl.php',
    'filepath' => 'hooks'
);


回答4:

Uhm, well, an dirty but straight to the point way would be to make a small hack to the core Uri class. Open the uri.php file inside system/core/ , scroll to line 269 where you have the method _explode_segments() and make them lowercase. Bad method, but should work.

function _explode_segments()
{
    foreach (explode("/", preg_replace("|/*(.+?)/*$|", "\\1", $this->uri_string)) as $val)
    {
        // Filter segments for security
        $val = trim($this->_filter_uri($val));

        if ($val != '')
        {
                    // $this->segments[] = $val;  // <--- ORIGINAL
            $this->segments[] = strtolower($val);   // <--- CHANGED
        }
    }
}  

Just consider that if you upgrade your install this changes will be overwritten, but they're so small anyway. Alternatively, you might go for a pre_system hook, but I think it would be much more difficult

Also, in routes you should not use leading or trailing slashes, so it must be

$route['companyname'] = "profile/1";


回答5:

Maybe you can use strtolower in your _remap function. It isn't sure that works, it was just an idea ;)



回答6:

The easiest way I could think of is to enforce lowercase urls with mod_rewrite (if you're using apache...)

RewriteMap  lc int:tolower
RewriteCond %{REQUEST_URI} [A-Z]
RewriteRule (.*) ${lc:$1} [R=301,L]

Source: http://www.chrisabernethy.com/force-lower-case-urls-with-mod_rewrite/



回答7:

Use Router:

$urix = substr(strtolower($_SERVER['REQUEST_URI']), 1);

$route["(?i)$urix"] = $urix;

Solution for all Case Insensitive Routings..



回答8:

IN Directory system/core/uri.php

search about

$this->_parse_request_uri()

you will find 2 replace them with

strtolower($this->_parse_request_uri())