Reputation: 141
I am using CodeIgniter and have a login system. I am still fairly new with php and I am wondering once the user is logged in, how I can access his/her data to use throughout the site? Right now I am trying to make it say welcome "username" but I dont know where the variables come from and how I should use them. Right now in my home_view.php I have:
<div class="main">
<h2>Welcome <?php echo $username; ?>!</h2>
</div>
It throws this error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: username
Filename: views/home_view.php
Line Number: 22
Can someone tell me how to do this?
Upvotes: 0
Views: 88
Reputation: 729
ok when user is logged in you need to store his or her data to session . when you verify user get his or her data and store that in session.
$data = array(
'username' => 'johndoe',
'email' => '[email protected]',
'logged_in' => TRUE
);
$this->session->set_userdata('logged_info', $data );
and then you can get it any where like
$userdata = $this->session->userdata('logged_info');
Upvotes: 0
Reputation: 11
Question: How do you access a logged-in user's data for use throughout the site?
The logged-in user specific data is usually stored in a session. For codeigniter, you can access session data using $this->session->userdata('item');
, or for example $this->session->userdata('username');
.
However, if you are using a specific login system it depends on the login system that you are using.
Custom Login System
After receiving the login information from a login form, pass the data to the session using the following:
$newdata = array(
'username' => 'johndoe',
'email' => '[email protected]',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
Then refer to the username with the following:
$this->session->userdata('username');
See Adding Custom Session Data in the Codeigniter Documentation.
Login System Example
A popular codeigntier authentication library is Tank-Auth.
When using Tank-Auth, after a user is logged in, you can call $this->tank_auth->get_username()
(which calls $this->ci->session->userdata('username')
, as mentioned above). This can then be stored and passed to a view.
In Tank-Auth you will see:
application/controller/welcome.php
$data['user_id'] = $this->tank_auth->get_user_id();
$data['username'] = $this->tank_auth->get_username();
$this->load->view('welcome', $data);
application/views/welcome.php
Hi, <strong><?php echo $username; ?></strong>! You are logged in now.
Upvotes: 1