Welcome Guest, Not a member yet? Register   Sign In
Global logged in/out variable
#1

[eluser]Stompfrog[/eluser]
Hi,

In my header view i have the following code...

Code:
if($this->session->userdata('username')){
        $username = $this->session->userdata('username');
        $userID = $this->session->userdata('userID');
        $logged = true;
    }
    else{
        $logged = false;
    }

I then use this $logged variable to alter the appearance of the header dependent on wether or not a user is logged in.

I have just tried to use this same $logged variable further down the page in another view file but it is generating errors. I assumed that if i set up a variable in the first view i pull into my controller the same variable would already exist when i pull in the 2nd, 3rd views etc. Clearly this is not the case.

What is the easiest/best way to have a globally available $logged variable that can be used in all views?
#2

[eluser]gon[/eluser]
You could declare the $logged var as global, writing

global $logged; at the beginning of the function where it is set.

Or you could use a helper to access $logged from any place of the app.
Also, a library for managing auth wouldn't hurt. So the logic wouldn't be present at the controllers.
#3

[eluser]Colin Williams[/eluser]
I, too, think you should have a method or function you call that returns TRUE or FALSE if the current user has authorized access.

Code:
if (user_access())
{
   // Do something for authenticated
}
else
{
   // Do something for anonymous
}
#4

[eluser]Randy Casburn[/eluser]
@Stompfrog -- Something like this would be another possible solution:

Code:
class Welcome extends Controller
{
    function Welcome()
    {
        parent::Controller();
    }

    function index()
    {
        if($this->session->userdata('username')){
                $data['username'] = $this->session->userdata('username');
                $data['userID'] = $this->session->userdata('userID');
                $this->load->view('logged/header', $data);
            }
        else{
                $this->load->view('unlogged/header');
        }
      $this->load->view('home');
      $this->load->view('footer');
   }
}

There is a proper CI way of "Adding Dynamic Data to the View" and that discussion can be found under that heading on this page: http://ellislab.com/codeigniter/user-gui...views.html



Randy




Theme © iAndrew 2016 - Forum software by © MyBB