How to get session array data CodeIgniter - php

I'm not quite sure why the username didn't appear on view page if i change the session data into array (i'm new in CodeIgniter). I have auth controller to make login process:
function index() {
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'username', 'required|trim|xss_clean');
$this->form_validation->set_rules('password', 'password', 'required|trim|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('Login');
# code...
}
else {
$username = $this->input->post('username');
$password = $this->input->post('password');
$check = $this->M_login->check($username, $password);
// session data
if ($check->num_rows() == TRUE) {
foreach ($check->result() as $value) {
$sess_data['id'] = $value->id;
$sess_data['name'] = $value->name;
$sess_data['username'] = $value->username;
$sess_data['password'] = $value->password;
$sess_data['description'] = $value->description;
$this->session->set_userdata($sess_data);
}
redirect('Dashboard');
}
else {
$this->session->set_flashdata('result_login', '<br>Invalid username or password, try again.');
redirect('Login');
}
And here is my dashboard controller:
public function __construct() {
parent::__construct();
if(!$this->session->userdata('id')){
redirect('login');
}
}
public function index() {
// Dashboard view
$username = $this->session->userdata('username');
$data['username']=$username;
$this->load->view('Dashboard', $data);
}
function logout() {
$this->session->sess_destroy('id');
redirect('login');
}
With above code, i can get the username on my dashboard view by echo $username. But when i change the session data like this:
if ($check->num_rows() == TRUE) {
foreach ($check->result() as $value) {
// session data
$sess_data = array(
'id' => $value->id,
'username' => $value->username,
'password' => $value->password,
'name' => $value->name,
'description' => $value->description
);
$this->session->set_userdata('log',$sess_data);
}
}
And Dashboard controller changed like this:
if(!$this->session->userdata('id')) {
$getdata= $this->session->userdata('log');
$data['username'] = $getdata['username'];
}
$this->load->view('Dashboard', $data);
Then the username disappeared from view page. How can i store username in session array and call it in view page. Please share your better suggestions or your experience guys.
Thanks.

Adding data in session :-
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
Retrieving Data from session :-
$this->session->all_userdata()
Retrieving single data :-
$session_id = $this->session->userdata('username');

Youcan refer this code
public function loginaction()
{
$this->load->library('session');
$a = $this->input->post('email');
$b = trim($this->input->post('password'));
$b1 = md5($b);
$c = 1;
$data = $this->userdata->userlogin($a,$b1,$c);
if($data)
{
echo true;
foreach ($data as $login)
{
$uid=$this->session->set_userdata('logId',$login->usr_id);
}
}
else
{
echo "Invalid username or password..!!!!";
$a=$this->input->post('email');
}
}

You can do it like
$username = $this->input->post('username');
$password = $this->input->post('password');
$check = $this->M_login->check($username, $password);
if ($check->num_rows() > 0)
{
$value = $check->row();
$sess_data['id'] = $value->id;
$sess_data['name'] = $value->name;
$sess_data['username'] = $value->username;
$sess_data['password'] = $value->password;
$sess_data['description'] = $value->description;
$this->session->set_userdata($sess_data);
redirect('Dashboard');
}
else
{
$this->session->set_flashdata('result_login', '<br>Invalid username or password, try again.');
redirect('Login');
}
And in your view
$username = $this->session->userdata('username');

Related

session checking is not working after uploading to server

this is my controller for login
public function user_login_process()
{
$this->form_validation->set_rules('username', 'username', 'trim|required');
$this->form_validation->set_rules('password', 'password', 'trim|required');
if ($this->form_validation->run() == false)
{
if(isset($this->session->userdata['logged_in']))
{
$this->load->view('admin/intropage');
}
else
{
$this->load->view('admin/login/login_dashboard');
}
}
else
{
$data = array('username' => $this->input->post('username'),'password' => md5($this->input->post('password')));
$result = $this->gt_login_model->login($data);
if ($result == true)
{
$username = $this->input->post('username');
$result = $this->gt_login_model->read_user_information($username);
if ($result != false)
{
$session_data = array('username' => $result[0]->user_name);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->load->view('admin/intropage');
}
}
else
{
$data = array('error_message' => 'Invalid Username or Password');
$this->load->view('admin/login/login_dashboard', $data);
}
}
}
this is the code that i used to check whether the session is set or not in other pages
if(!$this->session->userdata['logged_in'])
{
redirect("gt_login");
}
else
{
}
but this checking doesnot works ie, in other pages
$session_data = array('username' => $result[0]->user_name);
the value inside this array is not available.This problem is only when i uploaded my project to the server . But when i woked in local host this whole project works fine .
now the main problem is i cant check wheather the session is set or not in other pages .

best way to implement Codeigniter login

Here's my login controller index function:
public function index() {
$data['title'] = 'Login';
$this->load->view('login_form', $data);
}
then here's my validate_credentials function:
public function validate_credentials() {
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run() == FALSE) {
$this->index();
} else {
$this->load->model('user_model');
if ($this->user_model->checkUserAccess($this->input->post('username'))) { // checks if user has access to the site
if ($this->ldapAuth()) { // checks if successful authentication with LDAP server
$email = $this->user_model->getEmail($this->input->post('username'));
$gpcid = $this->user_model->getUserGPC($this->input->post('username'));
$this->user_model->updateTimestamp('users', 'DateLastLogin', 'UserID', $this->input->post('username'));
$data = array (
'username' => $this->input->post('username'),
'gpcid' => $gpcid,
'email' => $email,
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('profile');
} else { // unsuccessful login
$error = "Username and/or Password is incorrect";
$data['title'] = 'Login';
$data['message'] = $error;
$this->load->view('login_form', $data);
}
} else {
$error = "You do not have access to the site";
$data['title'] = 'Login';
$data['message'] = $error;
$this->load->view('login_form', $data);
}
}
}
Is there a way to just call the index function and pass the error message rather than loading the view multiple times?
$data['title'] = 'Login';
$data['message'] = $error;
$this->load->view('login_form', $data);
Instead of loading view file you have to redirect it to index function. And use Session flash data to achieve this.
Like,
Controller
$this->session->set_flashdata( 'error', 'Username and/or Password is incorrect' );
redirect('index');
To print the message on login_form.php view file,
View (login_form.php)
<?php if($this->session->flashdata('error')){
echo $this->session->flashdata('message');
}?>
Your Controller
public function validate_credentials() {
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run() == FALSE) {
$this->index();
} else {
$this->load->model('user_model');
if ($this->user_model->checkUserAccess($this->input->post('username'))) { // checks if user has access to the site
if ($this->ldapAuth()) { // checks if successful authentication with LDAP server
$email = $this->user_model->getEmail($this->input->post('username'));
$gpcid = $this->user_model->getUserGPC($this->input->post('username'));
$this->user_model->updateTimestamp('users', 'DateLastLogin', 'UserID', $this->input->post('username'));
$data = array (
'username' => $this->input->post('username'),
'gpcid' => $gpcid,
'email' => $email,
'is_logged_in' => true
);
$this->session->set_flashdata($data);
redirect('profile');
} else {
$userdata = array (
'error' =>'Username and/or Password is incorrect',
);
$this->session->set_flashdata($userdata);
redirect('redirect url here'); // here is your url for index
}
} else {
$userdata = array (
'error' =>'You do not have access to the site',
);
$this->session->set_flashdata($userdata);
redirect('redirect url here'); // here is your url for index
}
}
}
Controller
public function loginaction() {
$this->load->library('session');
$a = $this->input->post('email');
$b = trim($this->input->post('password'));
$b1 = md5($b);
$c = 1;
$data = $this->userdata->userlogin($a, $b1, $c);
if($data) {
echo true;
foreach ($data as $login) {
$uid = $this->session->set_userdata('logId', $login->usr_id);
}
} else {
echo "Invalid username or password..!!!!";
$a = $this->input->post('email');
}
}

How to set userid into a session array in codeigniter?

I'm a bit new to Codeigniter, so I need some help, please if you can just post here the answer. Thank you.
Here is my Controller:
public function login()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|min_length[3]');
$this->form_validation->set_rules('passwd', 'Passwd', 'required|min_length[3]');
$data = array();
if ($this->form_validation->run())
{
$email = $this->input->post('email');
$passwd = $this->input->post('passwd');
$this->load->model('user_model');
if ($this->user_model->check($email, $passwd))
{
$this->session->set_userdata('user', $email);
redirect(base_url('/'));
}
else
{
$data['error'] = 'Wrong e-mail or password.';
}
}
$this->load->view('login', $data);
}
and here is my Model:
public function __construct()
{
// Call the CI_Model constructor
parent::__construct();
}
public function check($email = NULL, $password = NULL)
{
$this->db->select('id');
$this->db->where('email', $email);
$this->db->where('password', sha1($password));
$this->db->limit(1);
$result = $this->db->get('php_users_login');
return ($result->num_rows() == 1);
}
I would like to put user-id into the session (database structure like id, email, password...)
Thank you for helping!
try this
Model
$this->db->select('id');
$this->db->where('email', $email);
$this->db->where('password', sha1($password));
$this->db->limit(1);
$result = $this->db->get('php_users_login');
return $result->row();
Controller
$checkData=$this->user_model->check($email, $passwd);
if(count($checkData)==1){
$this->session->set_userdata('user_id', $checkData->id);
}
Try this
In Controller
public function login()
{
$this->load->library('form_validation');
$this->load->model('user_model');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|min_length[3]');
$this->form_validation->set_rules('passwd', 'Passwd', 'required|min_length[3]');
$data = array();
if ($this->form_validation->run())
{
$email = $this->input->post('email');
$passwd = $this->input->post('passwd');
$result = $this->user_model->check($email, $passwd);
if ($result == true)
{
$newdata = array(
'email' => $email,
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
$this->load->view('home', $data); # load view
}
else
{
$data['error'] = 'Wrong e-mail or password.';
$this->load->view('login', $data);
}
}
else{
echo "Form validation Error";
}
}
In model
public function check($email, $password)
{
$query = $this->db->query("SELECT * FROM php_users_login WHERE email = '$email' AND password = sha1('$password') ");
$result = $query->result_array();
$count = count($result);
if (empty($count) || $count > 1 ) {
return false;
}
else{
return true;
}
}
You can set userid in session as:
Use this in your model:
public function check($email = NULL, $password = NULL)
{
$userid = 0;
$this->db->select('id');
$this->db->where('email', $email);
$this->db->where('password', sha1($password));
$this->db->limit(1);
$result = $this->db->get('php_users_login');
if($result->num_rows() == 1){
$data = $query->result_array();
$userid = $data[0]['id'];
}
return $userid;
}
In Controller:
// if login successfull
$this->load->model('user_model');
$userid = $this->user_model->check($email, $passwd);
if ($userid > 0)
{
// session array
$session_data = array(
'session_userid' => $userid,
'session_email' => $email
);
$this->session->set_userdata($session_data);
redirect(base_url('/'));
}
else
{
$data['error'] = 'Wrong e-mail or password.';
}
Side Note:
I didn't see session library included in your code, make sure you are using in autoload.php or included in the same controller.
$this->load->library('session');

Password is not matching while logging in

I have this code while registering the form:
function register()
{
$this->form_validation->set_rules('txt_username', 'Username', 'trim|required');
$this->form_validation->set_rules('cpassword', 'Confirm Password', 'trim|required|matches[txt_password]|md5');
$this->form_validation->set_rules('txt_password', 'Password', 'trim|required|md5');
//other codes
$data = array('username' => $this->input->post('txt_username'),
'password' => $this->input->post('txt_password')
);
// insert form data into database
if ($this->account_model->insertUser($data));
{
$this->session->set_flashdata('msg','successfully registered!');
redirect('account/register');
}
}
the password matches here.
but when i use same data to username and password to login: it displays invalid username or password:
the login function is as follows:
function login()
{
//set validations
$this->form_validation->set_rules("txt_username", "Username", "trim|required");
$this->form_validation->set_rules("txt_password", "Password", "trim|required");
$username = $this->input->post("txt_username");
$password = $this->input->post("txt_password");
$usr_result = $this->account_model->get_user($username, $password);
if ($usr_result > 0) //active user record is present
{
$this->account_model->login();
$data['message'] ="You are logged in!";
}
else
{
$this->session->set_flashdata('msg', 'Invalid username and password!');
}
}
}
I have this model for inserting registration form data to database:
function insertUser($data)
{
return $this->db->insert('user', $data);
}
and i have this model to retreive data to login:
function get_user($usr, $pwd)
{
$sql = "select * from user where username = '" . $usr . "' and password = '".md5($pwd). "'";
$query = $this->db->query($sql);
return $query->num_rows();
}
The best method instead of MD5 is use base64 in Codeigniter. That means decode() and encode().
Encoding
$password = 'mYp#ssw0rd'; // or $password
$encriptKey = 'super-secret-key';
$encrypted_string = $this->encrypt->encode($password, $encriptKey);
Decoding
$password = 'mYp#ssw0rd'; // or $password
$encriptKey = 'super-secret-key';
$decrypted_string = $this->encrypt->decode($password, $encriptKey);
In Addition
Load library as well $this->load->library('encrypt');
You could do this in your model:
public function login()
{
$user = $this->get_by(array(
'email' => $this->input->post('email'),
'password' => $this->hash($this->input->post('password')),
), TRUE);
if (count($user))
{
// Log in user
$data = array(
'name' => $user->name,
'email' => $user->email,
'id' => $user->id,
'user_type'=>$user->user_type,
'emp_id'=>$user->emp_id,
'loggedin' => TRUE,
);
$this->session->set_userdata($data);
return TRUE;
}
return FALSE;
}
public function logout ()
{
$this->session->sess_destroy();
$this->session->unset_userdata('logged_in','id','name','email');
}
public function loggedin ()
{
return (bool) $this->session->userdata('loggedin');
}
public function hash ($string)
{
return hash('sha512', $string . config_item('encryption_key'));
}
And can let a user login. Use CI Session for login which would be a better option.
Read More here
For Controller Do this:
public function login()
{
$dashboard ='admin/dashboard';
$rules = $this->secure_m->rules;
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() == TRUE)
{
if ($this->secure_m->login() == TRUE)
{
$this->secure_m->loggedin() == FALSE || redirect($dashboard);
redirect($dashboard);
}
else
{
$this->session->set_flashdata('error', 'That email/password combination does not exist');
redirect('secure/login', 'refresh');
}
}
$this->load->view("Your View");
}
Please store encrypted password at insert time.
for example:
$data['password'] = md5($data['password']);
I think it will resolve your problem.
Other code is working fine for me.

Codeigniter access session in view

function login(){
$data = array('username' => $_POST['username'], 'password' => $_POST['password']);
$this->form_validation->set_rules('username', 'Username', 'required|callback_username_check');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run() == FALSE){
$this->load->view('Login');
} else {
$result = $this->LoginModel->account_check($data);
if($result){
if($result['status'] = 'admin'){
$isLoggedin = array('user_type' => 'administrator' ,'admin_name' => $result['username'] , 'is_loggedin' => TRUE);
$this->session->set_userdata($isLoggedin);
$this->load->view('admin/homepage');
} else if($result['status'] = 'user'){
$isLoggedin = array( 'user_name' => $row['username'] , 'user_type' => 'user' , 'is_loggedin' => TRUE);
$this->session->set_user($isLoggedin);
$this->load->view('user/homepage');
}
}
}
}
function username_check($username){
$result = $this->LoginModel->username_check($username);
if($result != TRUE){
$this->form_validation->set_message('username_check' , 'Username does not exist');
return FALSE;
} else return TRUE;
}
MODEL:
function username_check($username){
$query = $this->db->get_where( 'admin' , array('username' => $username))->result_array();
if(!empty($query)){
return TRUE;
}else{
$query = $this->db->get_where( 'user_mst', array('username' => $username))->result_array();
if(!empty($query)){
return TRUE;
}else return FALSE;
}
}
function account_check($data){
$query = $this->db->get_where( 'admin' , array( 'username' => $data['username'] , 'password' => $data['password'] ))->result_array();
if(!empty($query)){
foreach($query as $row){
$result['status'] = 'admin';
$result['username'] = $row['username'];
$result['password'] = $row['password'];
return $result;
}
} else{
$query = $this->db->get_where( 'user_mst' , array( 'username' => $data['username'] , 'password' => $data['password'] ))->result_array();
if(!empty($query)){
foreach($query as $row){
$result['status'] = 'user';
$result['username'] = $row['username'];
$result['password'] = $row['password'];
return $result;
}
}
}
}
How do i access the user data, im going to use this to run an if per view if an account is logged in and if it is an admin acc.
I would like to read some opinion regarding how im using the session if i am 100% correct.
Also, i have a question,
This code <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?>
blocks direct access to the view, prevents view access but not specifically checks if a user is logged in.
How can i utilize this with the session. If its redundant please tell me,
Codeigniter passes data to the view with a second parameter:
$this->load->view('user/homepage');
doesn't pass any data.
$this->load->view('user/homepage', $data);
Would pass in a $data variable that you could use. (https://ellislab.com/codeigniter/user-guide/general/views.html)
Another point - I'd consider using the redirect() function after a successful login rather than loading the view you want in the login method. Use the URL Helper to do this (https://ellislab.com/codeigniter/user-guide/helpers/url_helper.html).
Hope that helps.

Categories