phpcodeigniterurlhttp-redirect

Codeigniter - url segment replace or redirect


I have a base controller (base) which all other controllers extend from. Anything placed here will override other controllers, the redirects will be here.

URLs example:

 http://domain.com/controllerone/function
 http://domain.com/controllertwo/function
 http://domain.com/controllerthree/function

Using the code below. will give me the controller name

$this->uri->segment(1);

Each of the above controllers need to be redirected to separate URLs, but the funcation part should not change:

 http://domain.com/newcontrollerone/function
 http://domain.com/newcontrollertwo/function
 http://domain.com/newcontrollerthree/function

In my base controller i want the following logic:

    $controller_name =   $this->uri->segment(1);

    if($controller_name === 'controllerone'){
       // replace the controller name with new one and redirect, how ?
    }else if($controller_name === 'controllertwo'){
     // replace the controller name with new one and redirect, how ?
    }else{
        // continue as normal
   }  

i was thinking i should use redirect() function and str_replace(), but dont know how efficient these would be. Ideally i do not want to use the Routing class.

thanks.


Solution

  • CodeIgniter's URI Routing, should be able to help in this case. However, if you have a good reason not to use it, then this solution may help.

    The potential redirects are in an array, where the key is the controller name being looked for in the URL and the value is the name of the controller to redirect to. This may not be the most efficient but I think it should be easier to manage and read than a potentially very long if-then-else statement.

    //Get the controller name from the URL
    $controller_name = $this->uri->segment(1);
    //Alternative: $controller_name = $this->router->fetch_class();
    
    //List of redirects
    $redirects = array(
        "controllerone" => "newcontrollerone",
        "controllertwo" => "newcontrollertwo",
        //...add more redirects here
    );
    
    //If a redirect exists for the controller    
    if (array_key_exists($controller_name, $redirects))
    {
        //Controller to redirect to
        $redirect_controller = $redirects[$controller_name];
        //Create string to pass to redirect
        $redirect_segments = '/'
                           . $redirect_controller
                           . substr($this->uri->uri_string(), strlen($controller_name)); //Function, parameters etc. to append (removes the original controller name)
        redirect($redirect_segments, 'refresh');    
    }
    else
    {
        //Do what you want...
    }