Search code examples
phpcodeigniterhttp-referer

Redirect to referer url in codeigniter


In messaging system of my project when you get a message from a user you a email alert saying that the another user has sent a message to view the message click here (i.e the url of message) So if the user is not logged in to system he gets redirect to login page and after login it should get back to the referer url. I have made a basecontoller in core folder and extending the CI_controller the authenticating code is as follows.

function authenticate($type = 'user')
    {
        if($type == 'user')
        {
            if($this->user_id)
            {
                // user is logged in. check for permissions now
            }
            else
            {
                // user isnt logged in. store the referrer URL in a var.
                if(isset($_SERVER['HTTP_REFERER']))
                {
                    $redirect_to = str_replace(base_url(),'',$_SERVER['HTTP_REFERER']);
                }
                else
                {
                    $redirect_to = $this->uri->uri_string();
                }            

                redirect('user/login?redirect='.$redirect_to);
                exit;
            }
        }

        if($type == 'admin')
        {
            if($this->session->userdata('admin_id') && $this->session->userdata('user_type') ==5)
            {
                // Admin is logged in
            }
            else
            {
                redirect('admin/login');
                exit;
            }
        }
    }

The referer url is "http://example.com/project/pm/view_conversation?id=11" now the problem is I am getting referer url till view_conversation and not able to get the id part.

Any suggestion ?

Thank you.


Solution

  • This can help:

    CI 2+ https://www.codeigniter.com/userguide2/libraries/user_agent.html

    CI 3+ http://www.codeigniter.com/userguide3/libraries/user_agent.html

    Below solution is for Codeigniter version 3

    $this->load->library('user_agent');
    if ($this->agent->is_referral())
    {
        echo $this->agent->referrer();
    }
    

    UPDATE: interesting and useful information on how to obtain referrer information with the same user_agent library
    https://www.tutorialandexample.com/user-agent-class/