Reputation: 33
I was surfing the net and found official page :
With Adding Custom Session Data paragraph
https://www.codeigniter.com/user_guide/libraries/sessions.html
I tried implement the code to mine but it still doesnt work:
public function login_validation(){
$data = new stdClass();
$this->load->database(); // load database
$this->load->library('form_validation');
$this->load->helper('url');
$this->load->library('session');
$this->form_validation->set_rules('email', 'email', 'required|trim|callback_validate_credentials');
$this->form_validation->set_rules('password', 'password', 'required|trim', array(
'required' => 'Password field is empty'));
$this->load->model("model_users");
$email = $this->input->post('email');
$user_id = $this->model_users->get_user_id($email);
$user = $this->model_users->get_user($user_id);
if ($this->form_validation->run()){
$newdata = array(
'username' => 'johndoe',
'email' => '[email protected]',
'logged_in' => TRUE
);
// $_SESSION['user_id'] = (bool)true;
// $_SESSION['email'] = $this->input->post('email');
// $_SESSION['logged_in'] = (bool)true;
// $_SESSION['username'] = (string)$user->priv;
$this->session->set_userdata($newdata);
$this->members();
} else{
$this->login();
}
}
Im getting this error in this line - <?php echo $_SESSION['username']; ?>
:
A PHP Error was encountered
Severity: Notice
Message: Undefined index: username
Filename: views/catalog.php
Line Number: 19
Backtrace:
I dont see any mistake and Im really anxious right now , because nothing is working. Sorry for bad formulation of question. If you need extra code lines just say I will paste it in pastebin.com
Upvotes: 0
Views: 222
Reputation: 375
Since PHP native session are not implemented in CI:2 so you can't use $_SESSION in codeigniter 2 rather you can use
$this->session->set_userdata('key','data');
//to fetch this session you can do
$this->session->userdata('key');
But due to some reason you need to implement PHP native session you can add this as a library Check library here
Upvotes: 0
Reputation: 38584
Setting new session
$newdata = array(
'username' => 'johndoe',
'email' => '[email protected]',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata); # setting session data
Retrieving the session
$username = $this->session->userdata('username');
echo $username;
In view
echo $this->session->userdata('username');
Note:
If you want to passing the session data to view you can bind it with
$data[]
or in view can call it directly.
Upvotes: 1