Codeigniter router to pass url segment as $_GET qu

2019-08-23 03:03发布

How can I set codeigniter to route this:

/download/folder/file.ext

to this

/download?path=folder/file.ext

?

I know how to do it using .htaccess , but is it possible in CI only? I tried

$route['download/(:any)'] = "download/index/?path=$1"; 

didn't work ... thanks

1条回答
Luminary・发光体
2楼-- · 2019-08-23 03:26

I urge you to change your perspective of what the CI Router class does (this was the most difficult thing for me in moving from the "rewriting" approach to the "router" approach).

Your question assumes a "rewriting" approach, and here's how it could be handled with an .htaccess file:

RewriteRule ^/download/(.*)$ index.php/download/?path=$1 [L]

Under this approach, you'll have a route to match just the "/download" part, and then you'll use $this->input->get('path') in the controller action.

The "routing" approach keeps the .htaccess file the same, and changes your $routes configuration, as well as how the controller "gets" that information, if you will:

<?php
// config/routes.php change:
$routes['download/(:any)'] = 'download/index/$1';

// controllers/download.php:
class Download extends CI_Controller {
    public function index($folder, $file)
    {
        // if the folder is "flat" (i.e. no subfolders),
        // you can simply use $folder and $file
        var_dump($folder);
        var_dump($file);

        // otherwise, $file is the last segment ("n"),
        // and folder is segments 2 through n
        $segments = $this->uri->segment_array();
        $folder = implode('/', array_slice($segments, 2, -1);
        $file   = end($segments);

        // full path is always $folder and $file appended
        $path = $folder.'/'.$file;
        var_dump($path);
    }
}

This is the approach, so adjust as needed for your specific requirements.

Cheers!

查看更多
登录 后发表回答