Passing variables before controller URI segment in CodeIgniter

穿精又带淫゛_ 提交于 2019-12-02 02:40:21

Is this what you're after:

$route['(:any)/(:any)'] = '$2/$1';

where all your function definitions have the username as the last parameter:

class Controller{function page(var1, var2, ..., varn, username){}}

Or, if you only want in on one specific page you could do something like this:

$route['(:any)/controller/page/(:any)'] = 'controller/page/$2/$1'; //This will work for the above class.

Or, if you want it for a number of functions in a controller you could do this:

$route['(:any)/controller/([func1|func2|funcn]+)/(:any)'] = 'controller/$2/$3/$1';

After messing with this problem for a day I ended up with adding custom router class to my project. I'm working in CodeIgniter 2.0, so the location of this file should be application/core/MY_Router.php

My code is following:

class MY_Router extends CI_Router {

// --------------------------------------------------------------------

/**
 * OVERRIDE
 *
 * Validates the supplied segments.  Attempts to determine the path to
 * the controller.
 *
 * @access    private
 * @param    array
 * @return    array
 */
function _validate_request($segments)
{
    if (count($segments) == 0)
    {
        return $segments;
    }

    // Does the requested controller exist in the root folder?
    if (file_exists(APPPATH.'controllers/'.$segments[0].EXT))
    {
        return $segments;
    }

    $users["username"] = 1;
    $users["minu_pood"] = 2;
    // $users[...] = ...;
    // ...
    // Basically here I load all the 
    // possbile username values from DB, memcache, filesystem, ...
    if (isset($users[$segments[0]])) { 
        // If my segments[0] is in this set
        // then do the session actions or add cookie in my cast.
        setcookie('username_is', $segments[0], time() + (86400 * 7));
        // After that remove this segment so 
        // rounter could search for controller!
        array_shift($segments); 
        return $segments;
    }

    // So segments[0] was not a controller and also not a username...
    // Nothing else to do at this point but show a 404
    show_404($segments[0]);

}

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!