How to set userid into a session array in codeigniter? - php

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');

Related

codeigniter login 2 user

I have 2 user and I want to make 2 pages. if user A logs in, I will show page A and if user B logs in, I will show page B.
How to make controller for that?
my controller
public function cekLogin()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required|callback_cekDb');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login/login');
} else {
if($username=='admin'){
redirect('Home','refresh');
} else {
redirect('HomeMavens','refresh');
}
}
}
my model:
public function login($username, $password)
{
$this->db->select('id_user, username, password');
$this->db->from('user');
$this->db->where('username', $username);
$this->db->where('password', MD5($password));
$query = $this->db->get();
if($query->num_rows()==1){
return $query->result();
}else {
return false;
}
}
it is easy with if and else. like this.
if($query->num_rows() > 0){
if($query->row()->name == 'a'){
$this->load->view('page_A');
}
elseif($query->row()->name == 'b'){
$this->load->view('page_B');
}
else{
$this->load->view('login');
}
}else {
return false;
}
My Controller
public function getlogin(){
$this->form_validation->set_rules('email_address', 'Email', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_validatelogin');
if($this->form_validation->run() == FALSE){
$message = "Invalid Login Details";
$this->session->set_flashdata('message', $message);
redirect(base_url());
}else{
$data = $this->usermodel->myaccountdetails();
if($data['type'] == '0'){
$this->load->view('pageA');
}else{
$this->load->view('pageB');
}
}
}
public function validatelogin(){
$credentials = array(
"email_address"=>$this->input->post('email_address'),
"password"=>md5($this->input->post('password'))
);
return $this->loginmodel->getlogin($credentials);
}
Login Model
public function getlogin($credentials){
$this->db->select('*');
$this->db->from("tbl_login");
$this->db->where('email_address = ' . "'" . $credentials['email_address']. "'");
$this->db->where('password = ' . "'" . $credentials['password'] . "'");
$this->db->limit(1);
$query = $this->db->get();
if($query->num_rows() == 1){
$row = $query->row_array();
$this->session->set_userdata('admin', $row['id']);
return true;
}else{
return false;
}
}
User Model
function myaccountdetails()
{
$uid = $this->session->userdata('admin');
$sql = $this->db->query("select * from tbl_login where id = '".$uid."' ");
return $sql->row_array();
}

Password verify function in codeigniter for login

Hi all I have this issue when I validate log in in codeigniter that seems it does not check the required password in my database.The required password in my database is hash using this
$password_hash = password_hash($password, PASSWORD_BCRYPT);
How can i used password_verify function in my model code?
Here is my model code:
public function login($data) {
$condition = "username =" . "'" . $data['username'] . "' AND " . "password =" . "'" . $data['password'] . "'";
$this->db->select('*');
$this->db->from('users');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1)
{
return true;
} else
{
return false;
}
}
Here is my controller:
public function login_user()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean','required');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean','required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login_view');
} else {
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname')
);
$result = $this->login_database->login($data);
if ($result == TRUE) {
// Add user data in session
$this->session->set_userdata('username', $data['username']);
$this->session->set_userdata('firstname', $data['firstname']);
$this->session->set_userdata('lastname', $data['lastname']);
//redirect to dashboard
$this->load->view('include/sidenavbar');
$this->load->view('include/topnavbar');
$this->load->view('dashboard');
} else {
$this->session->set_flashdata('message', 'Login is invalid. Please try again!');
$this->load->view('login_view', $data);
}
}
}
can anyone help me how to do this..
Thanks in advance.
You should use password_verify() to know if you're password is valid.
Try this model function:
public function login($data) {
$this->db->select('password');
$this->db->from('users');
$this->db->where('username', $data['username']);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
$record = $query->row_array();
return password_verify($data['password'], $record['password']);
} else {
return false;
}
}
Hope this will help you :
after returning data from model you can check for correct password using password_verify()
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname')
);
$result = $this->login_database->login($data);
/*$result should return a single user data (in array form here)*/
if (! empty($result))
{
if (password_verify($data['password'], $result['password']))
{
$this->session->set_userdata('username', $data['username']);
$this->session->set_userdata('firstname', $data['firstname']);
$this->session->set_userdata('lastname', $data['lastname']);
//redirect to dashboard
redirect('dashboard'); /*use redirect()*/
//$this->load->view('include/sidenavbar');
//$this->load->view('include/topnavbar');
//$this->load->view('dashboard');
}
else
{
$this->session->set_flashdata('message', 'Password is invalid. Please try again!');
$this->load->view('login_view', $data);
}
}
else
{
$this->session->set_flashdata('message', 'Login is invalid. Please try again!');
$this->load->view('login_view', $data);
}
Your model should be like this :
public function login($data)
{
$this->db->where('username', $data['username']);
$query = $this->db->get('users');
if ($query->num_rows() == 1) {
$user = $query->row_array();
return $user;
} else {
return false;
}
}
Update : dashboard method
public function dashboard()
{
/*$data['title'] = 'my title';
you can pass data to the view like this
$this->load->view('dashboard',$data);
*/
$this->load->view('templates/header');
$this->load->view('dashboard');
$this->load->view('templates/footer');
}

I cannot login after registration(while checking:echo num_rows() is 0 although having records)

I am new to codeigniter, I am trying to login after registration... I enter correct user name and password, but error is "No such account exists in database" which set message in else part if its false.
For checking I used echo num_rows() it's showing 0 (which is wrong), total 5 records are there but echo num_fields is showing 8 fields (which is correct).
controller login code:
public function login() {
$this->form_validation->set_rules('username', 'User Name', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() === FALSE) {
$this->load->view('login');
} else {
//get user name
$username = $this->input->post('username');
//get encrypt password
$password = md5($this->input->post('password'));
//login user
$user_id = $this->auth_model->login($username, $password);
if ($user_id) {
//create session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => true
);
$this->session->set_userdata($user_data);
//set message
$this->session->set_flashdata("success", "your are logged in");
redirect('index.php/users/profile');
} else {
$this->session->set_flashdata("error", "No such account exists in database");
redirect('index.php/auth/login');
}
}
}
model login code:
public function login($username, $password) {
$this->db->where('username', $username);
$this->db->where('password', $password);
$result = $this->db->get('tblLogin');
if ($result->num_rows() == 1) {
return $result->row(0)->id;
} else {
return false;
}
}
public function login($username, $password) {
$this->db->where('username', $username);
$this->db->where('password', $password);
$result = $this->db->get('tblLogin');
$ret = $result->row();
if ($ret) {
return $ret;
} else {
return false;
}
}
row() function get is single and check in if condition.
print your query using $this->db->last_query();
and check your mysql database.
You can try this solution for your problem :
Changes your modal function:
Modal.php
public function login($username, $password) {
$this->db->where('username', $username);
$this->db->where('md5(password)', $password);
$result = $this->db->get('tblLogin');
$ret = $result->row();
if (!empty($ret)) {
return $ret;
} else {
return false;
}
}
Please changes your controller file.
LoginController.php
public function login() {
$this->form_validation->set_rules('username', 'User Name', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() === FALSE) {
$this->load->view('login');
} else {
//get user name
$username = $this->input->post('username');
//get encrypt password
$password = $this->input->post('password');
//login user
$user_id = $this->auth_model->login($username, $password);
if ($user_id) {
//create session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => true
);
$this->session->set_userdata($user_data);
//set message
$this->session->set_flashdata("success", "your are logged in");
redirect('index.php/users/profile');
} else {
$this->session->set_flashdata("error", "No such account exists in database");
redirect('index.php/auth/login');
}
}
}
Controller:
// log in user
public function login() {
$this->form_validation->set_rules('username', 'User Name', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() === FALSE) {
$this->load->view('users/login');
} else {
//get user name
$username = $this->input->post('username');
//get encrypt password
$password = $this->input->post('password');
//login user
$user_id = $this->auth_model->login($username, $password);
if ($user_id) {
//create session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => true
);
$this->session->set_userdata($user_data);
//set message
$this->session->set_flashdata("loggedin", "your are logged in");
redirect('dashboard');
} else {
$this->session->set_flashdata("log_failed", "Login invalid");
redirect('login');
}
}
}
Model:
public function login($username, $password) {
$this->db->where('username', $username);
$result = $this->db->get('tbllogin');
$db_password = $result->row(0)->password;
if (password_verify($password,$db_password)) {
return $result->row(0)->id;
} else {
return false;
}
}

How to get session array data CodeIgniter

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');

To check the account_status and log the account

In the below code i have used codeigniter in my database i have a column name account_status it will be inactive by default .Now i want to check the account_status if it is active it should make me login else not.Pls help me to do .
Controller:
function index()
{
$data['main_content'] = 'login_form';
$this->load->view('includes/template', $data);
}
function validate_credentials()
{
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if($query) // if the user's credentials validated...
{
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('site1/members_area');
}
else // incorrect username or password
{
$this->index();
}
}
Site1
function members_area()
{
$this->load->view('homepage_view');
}
model:
function validate()
{
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get('membership');
if($query->num_rows == 1)
{
return true;
}
}
You have these methods Just try this
Just use anther where condition in your model
function validate()
{
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', md5($this->input->post('password')));
$this->db->where('account_status','active');
$query = $this->db->get('membership');
if($query->num_rows == 1)
{
return true;
}
}
Or check the status in your controler
function validate_credentials()
{
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if($query) // if the user's credentials validated...
{
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
if($query->num_rows()>0)
$status = $query->row()->account_status;
else
$status = '';
if($status == 'active')
{
$this->session->set_userdata($data);
redirect('site1/members_area');
}
else //Account In active
{ $this->index(); }
}
else // incorrect username or password
{
$this->index();
}
}

Categories