0

With CodeIgniter framework, I have an admin page inside AdminController, inside its constructor I put a check if user is not logged-in then redirect to the login page.

And In LoginController after successful login, I want user to redirect to the previous admin page.

From different examples I tried:

$this->load->library('user_agent');
$this->session->set_userdata('redirect_back', $this->agent->referrer());

And also

$_SERVER['HTTP_REFERER']);

But both are returning me empty string.

How can I fix this problem.

Sparky
  • 98,165
  • 25
  • 199
  • 285
M_Idrees
  • 2,080
  • 2
  • 23
  • 53
  • So many ways to do this. [However, I would not use `http_referer`](https://stackoverflow.com/a/36240257/594235). Have you searched yet? https://stackoverflow.com/search?q=%5Bcodeigniter%5D+redirect+after+login – Sparky May 26 '18 at 14:46
  • Finally I did as suggested by @Karlo's answer. I not get idea why this user_agent library not working as expected, may be I did something wrong. – M_Idrees May 28 '18 at 07:50

1 Answers1

0

In your AdminController file, before redirecting to LoginController, save the current url to a session variable:

$referrer_value = current_url().($_SERVER['QUERY_STRING']!=""?"?".$_SERVER['QUERY_STRING']:"");
$this->session->set_userdata('login_referrer', $referrer_value);
// redirect to login page

In your LoginController, on successful login, check if session 'login_referrer' has value. If it has then redirect using the value of that.

if($this->session->userdata('login_referrer')!=""){
    $tmp_referrer = $this->session->userdata('login_referrer');
    $this->session->unset_userdata('login_referrer');
    redirect($tmp_referrer);
}

You may need to call the following to load the required library and helper for the above code to run successfully.

$this->load->helper('url');
$this->load->library('session');
Karlo Kokkak
  • 3,674
  • 4
  • 18
  • 33
  • 1
    Thanks @KarloKokkak, Thats how I used to do with my .net applications. Here I was just trying to follow codeigniter user_agent library, and php server variables array, as it was suggested in some articles. At-the-end this trick did the job. – M_Idrees May 28 '18 at 07:45