1
votes

I have got my site(mysite.com) to redirect to mysite.com/Mobile for mobile browsers using codeigniters useragent library from my default controller.

When I cache my output from the controller the redirect doesnt work as the browser is served the cached file.

Is there a proper way to go about redirecting from the config/routes.php file? Will this redirect mobile visitors?

My controller

class Child extends Controller {

function child()
{
    parent::Controller();
    //$this->output->cache(7200);
    $agent = $this->agent->browser() . ' ver ' . $this->agent->version();

}

function index()
{
    if ($this->agent->is_mobile())
    {
        header('Location: ' . site_url() . 'Mobile/', TRUE, 301);
        exit(0); 
    }else{
        $this->output->cache(7200);
        $this->load->view('home',$data);
    }
}
1

1 Answers

2
votes

I wouldn't suggest using CodeIgniter's output caching. That runs before the Controller, therefore you will never get in the index(). Routing can't deal with this situation as it isn't able to detect if the client is mobile.

It's a better idea to use the other caching method that CodeIgniter offers, as it's more granular, you can cache the single views. http://codeigniter.com/user_guide/libraries/caching.html

function index()
{
    // should put this in the __construct() of this controller or in your MY_Controller.php
    $this->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file'));

    if ($this->agent->is_mobile())
    {
        redirect('Mobile');
    }
    else
    {
        // if this doesn't get us the output, recreate and store it
        if(!$output = $this->cache->get('controllername_index_output'))
        {
            $output = $this->load->view('home', $data, TRUE);
            $this->cache->save('controllername_index_output', $output, 7200);
        }

        // now we surely have the output ready, whether it was cached or not
        $this->output->set_output($output);         
    }
}