Cant create a admin session in CI - php

I want to create a login system in CodeIgniter.
I have this in my controller:
public function user_login_process()
{
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$result = $this->login_database->login($data);
if ($result == TRUE) {
$username = $this->input->post('username');
$result = $this->login_database->read_user_information($username);
if ($result != false) {
$session_data = array(
'username' => $result[0]->username,
'email' => $result[0]->email,
);
$this->session->set_userdata('logged_in', $session_data);
if (isset($this->session->userdata['logged_in'])) {
if( $username="admin"){
$result1 = $this->login_database->read_admin_information($username);
if ($result1 != false) {
$session_data = array(
'username' => $result1[0]->username,
);
$this->session->set_userdata('admin', $session_data);
$this->load->view('admin_page');
}}}
else {
$this->load->view('home_page');
}}
} else {
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('login_form', $data);
}
//}
I have this in my model:
public function login($data) {
$condition = "username =" . "'" . $data['username'] . "' AND " . "password =" . "'" . $data['password'] . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}
// Read data from database to show data in admin page
public function read_user_information($username) {//Will read the data for loginn
$condition = "username =" . "'" . $username . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
public function read_admin_information($username) {//Will read the data for loginn
$condition = "username =" . "'" . $username . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
So I'm trying to create a session which differentiates a user if it is a normal or is admin(username=admin). The problem is that after I login like admin or not this always takes me to the admin page. What it should do: it should take me to the home_page if user is not admin but is logged in.
Have I done something wrong? I have read the session class of CI before I did this. Can someone help me to do this in right way? Thanks!

you are not comparing, you are assigning here:
if( $username="admin"){ // will assign 'admin' to $username
Should be:
if( $username=="admin"){ // will compare $username == 'admin'

try this sir: (if you have a usertype on your table)
for example:
User_Account:(The table)
User_type(1 is admin)(0 is client)
ID | First_name | Last_name | Username | Password | User_type
1 Michael Jordan MJ23 6rings 1
2 Kobe Bryant KB24 5rings 0
MODEL:
public function login($user,$pass){
$data = array(
'Username' => $user,
'Password' => $pass);
$query = $this->db->get_where('user_account',$data);
return $query->result_array();
}
VIEW:
<form action="<?php echo base_url(); ?>index.php/My_Controller/login_user" method="post">
Username: <input type="text" name="username"/><br/>
Password: <input type="password" name="password"/><br/>
<button type="submit">LOGIN</button>
</form>
CONTROLLER:
public function login_user(){
$user = $this->input->post('username');//this is from the name on input
$pass = $this->input->post('password');//this is from the name on input
$result=$this->My_Model->login($user,$pass);
$usertype = $result["0"]["User_type"];//this is from the database, whenever you login a user which is valid this is what you will use to see what is his User_type
if($usertype == 1){
redirect('My_Controller/show_admin');
}
else if($usertype == 0){
redirect('My_Controller/show_client');
}
}
Try this out: if you have questions just comment!

Related

how to verify the hashed password?

I am using CodeIgniter framework.
Below is the function contained in the Signup.php controller.
public function _hash_string($str){
$hashed_string = password_hash($str, PASSWORD_BCRYPT);
return $hashed_string;
}
public function _verify_hash($text, $hashed_string){
$result = password_verify($text, $hashed_string);
return result; //TRUE OR FALSE
}
public function index()
{
if($this->input->post('newuser') == 1)
{
$user = new Users_model();
$user->username = $this->input->post('username');
$user->email = $this->input->post('email');
$pass= $this->input->post('password');
$hashed_pass = $this ->_hash_string($pass);
$user->password = $hashed_pass;
$user->account_status = 1;
$user->user_role = $this->input->post('user_role');
$id = $this->usermodel->insert($user);
}else{
$this->load->view('signup-page');
}
I've successfully hashed the user's password. How can I verify them?
Below is the function contained in the Login.php controller.
public function index()
{
if($this->input->post('login') == 1)
{
$user = new Users_model();
$user->email = $this->input->post('email');
$user->password = $this->input->post('password');
$user->user_role = $this->input->post('user_role');
$results = $this->usermodel->login($user);
if(count($results) > 0)
{
foreach($results as $row)
{
$session_array = array(
"id" => $row['id'],
"username" => $row['username'],
"email" => $row['email'],
"password" => $row['password'],
"account_status" => $row['account_status'],
"user_role" => $row['user_role']
);
$this->session->set_userdata($session_array);
$url = base_url() . "home?login=success";
redirect($url, "refresh");
}
}else{
$url = base_url() . "login?login=failed";
redirect($url, "refresh");
}
}else{
$this->load->view('login-page');
}
}
And here is the Users_model.php model.
function login($user){
$conditions = array(
"email" => $user->email,
"password" => $user->password,
"user_role" => $user->user_role,
"account_status" => 1,
);
$this->db->select('*');
$this->db->from('users');
$this->db->where($conditions);
$rs= $this->db->get();
return $rs->result_array();
}
What should I do to properly log the user in?
You can't compare password in mysql. because hashed using php, you have to use php function to compare password.
function login($user){
$conditions = array(
"email" => $user->email,
//"password" => $user->password,
"user_role" => $user->user_role,
"account_status" => 1,
);
$this->db->select('*');
$this->db->from('users');
$this->db->where($conditions);
$rs= $this->db->get();
if(!empty($rs)) {
$result_array = $rs->row_array();
$controllerInstance = & get_instance();
if($controllerInstance->_verify_hash($user->password,$result_array['password']) == TRUE) {
return $result_array;
}
}
return false;
}
use get instance to access controller.
$controllerInstance = & get_instance();
$controllerData = $controllerInstance->_verify_hash();
Hope this helps. updated after zaph comment

codeigniter query resulting to null but the if condition doesn't satisfies

i am new in codeigniter and i am stuck with this if statement. I am selecting from my database the user_status and the user_type of the user and if it is null the value $res cant be empty.
if(empty($res)) {
echo "aaaa";
$this->index();
}
here is my full code in model :
<?php
class Login_model extends MY_Model {
function validate($data) {
$condition = "user_email =" . "'" . $data['useremail'] . "' AND " . "user_password =" . "'" . $data['password'] . "'";
$this->db->select('usertype_id,user_status');
$this->db->from('user');
$this->db->where($condition);
$query = $this->db->get();
if($query->num_rows() == 1) {
return $query->result();
}
else {
return NULL;
}
}
}
?>
my controller looks like this :
function validate_credentials() {
$this->load->model('login_model');
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$res['res'] = $this->login_model->validate($data);
if(empty($res)) {
echo "aaaa";
$this->index();
}
My question is, why this $res is always not empty. when i print_r the $res it shows an empty array.

Hitting same controller url method manually gives error in Codeigniter

I am new to Codeigniter i am stuck into a problem, i have searched every where but i did not find solution to it,
My problem is when i hit a particular controller method through a link it works perfectly for eg.
http://localhost/MyProject/indexController/user_login_process
but when i hit that method manually after it renders first time properly, it renders view but following error is there.
Please help me to sort out my issue:
Controller:
public function user_login_process() {
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
if(isset($this->session->userdata['logged_in'])){
$this->load->view('teaching');
}else{
$this->load->view('index');
}
} else {
$username=$this->input->post('username');
$data = array('username' => $this->input->post('username'),'password' => $this->input->post('password'));
$result = $this->login_database->login($data);
if ($result == TRUE) {
$result = $this->login_database->read_user_information($username);
if ($result != false) {
$session_data = array('id'=>$result[0]->id,'username' => $result[0]->email,'password' => $result[0]->password);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->session->set_userdata('user_info', $session_data);
$user_info=$this->session->userdata('user_info');
$u_id=$user_info['id'];
$data['query']=$this->teaching_model->get_all_courses($u_id);
$this->load->view('teaching', $data);
}
}
else
{
$data = array('error_message' => 'Invalid Username or Password');
$this->load->view('index', $data);
}
}
}
Model:
<?php
Class Teaching_model extends CI_Model {
function get_all_courses($u_id)
{
$condition = "u_id =" . "'" . $u_id . "'";
$this->load->database();
$this->db->select("*");
$this->db->from("course");
$this->db->where($condition);
$query=$this->db->get();
return $query->result();
}
}
teaching View:
foreach ($query as $row)
{ ?>
$row->name;
<? } ?>
Try this. All codes are changed. check carefully.
Change your controller name to Home.php and inside Home too. Bcz your URL contain index is something feal bad
In Controller
public function user_login_process() {
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE)
{
# I dont know purpose od this. For now i juts redirct to login
redirect('login');
/* if(isset($this->session->userdata['logged_in']))
{
$this->load->view('teaching');
}
else
{
$this->load->view('index');
}*/
}
else
{
$this->load->database();
$username = $this->input->post('username');
$password = $this->input->post('password');
$result = $this->login_database->login($username,$password);
if ($result == 0) {
echo "Invalid login";
}
elseif ($result == 1) {
echo "Multiple account matched. Contact admin";
}
else{
$session_data = array(
'id' =>$result[0]['id'],
'username' => $result[0]['email'],
'password' => $result[0]['password'],
'logged_in' => TRUE
);
# only set one sesstion
$this->session->set_userdata($session_data);
$id = $result[0]['id']; # logged User ID
$data['query']=$this->teaching_model->get_all_courses($id);
}
if ($result)
{
$result = $this->login_database->read_user_information($username);
if ($result != false)
{
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->session->set_userdata('user_info', $session_data);
$user_info=$this->session->userdata('user_info');
$u_id=$user_info['id'];
$result2 = $this->teaching_model->get_all_courses($u_id);
if($result2 == 0){
echo "No Courses Found";
}
else{
$data['query'] = $result2;
$this->load->view('teaching', $data);
}
}
}
else
{
$data = array('error_message' => 'Invalid Username or Password');
$this->load->view('index', $data);
}
}
}
In Model*(login_database)*
public function login($username,$password)
{
$query = $this->db->query("SELECT * FROM table_name WHERE username = '$username' AND password= '$password' ");
$result = $query->result_array();
$count = count($result);
if (empty($count)) {
return 0;
}
elseif ($count) >1) {
return 1;
}
else{
return $result;
}
}
In Model*(Teaching_model)*
Class Teaching_model extends CI_Model {
function get_all_courses($id)
{
$query = $this->db->query("SELECT * FROM course WHERE u_id = $id");
$result = $query->result_array();
$count = count($result);
if (empty($count)) {
return 0;
}
else{
return $result;
}
}
}
if it is an issue with session, try using database for managing sessions:
config.php
$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'ci_sessions';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
For MySQL:
Create a table named 'ci_sessions' in your database, all the sessions will be managed using this table, and it will help you when you are hosting the website / application , may avoid some possible errors with the session variables and the permissions :
CREATE TABLE IF NOT EXISTS `ci_sessions` (
`id` varchar(40) NOT NULL,
`ip_address` varchar(45) NOT NULL,
`timestamp` int(10) unsigned DEFAULT 0 NOT NULL,
`data` blob NOT NULL,
KEY `ci_sessions_timestamp` (`timestamp`)
);
**For Validating the users against their password **
public function validate_admin($username,$password)
{
// grab user input
if(isset($_POST['username']) AND $_POST['username'] !='')
{
$username = $this->security->xss_clean($this->input->post('username'));
$password = $this->security->xss_clean($this->input->post('password'));
}
$this->db->where('username', $username);
$this->db->where('password', $password);
$this->db->having("rec_status != 'C' ");
// Run the query
$query = $this->db->get('employee');
// Let's check if there are any results
if($query->num_rows() == 1)
{
// If there is a user, then create session data
$row = $query->row();
$data = array(
'id_admin' => $row->id,
'first_name' => $row->first_name,
'last_name' => $row->last_name,
'email_admin' => $row->email,
'phone_admin' => $row->phone,
'acc_status_admin' => $row->rec_status,
'acc_type_admin' => $row->emp_role,
'validated_admin' => true
);
$this->session->set_userdata($data);
return true;
}
// If the previous process did not validate
// then return false.
return false;
}

Session Doesn't work in codeigniter

In my project, session is work fine before few days.But now it doesn't work. i can't find the error. plsease help me. it displays error called Severity: Notice
Message: Undefined index: firstname
Filename: user_include/header.php
Line Number: 5
A PHP Error was encountered
Severity: Notice
Message: Undefined
index: id
Filename: user_include/header.php
Line Number: 7
controller
/ Check for user login process
public function user_login_process() {
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
if(isset($this->session->userdata['logged_in'])){
//$this->load->view('admin_page');
$this->home();
}else{
$this->load->view('user_site/login_form');
}
} else {
$data = array(
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
);
$result = $this->login_database->login($data);
if ($result == TRUE) {
$email = $this->input->post('email');
$result = $this->login_database->read_user_information($email);
if ($result != false) {
$session_data = array(
'firstname' => $result[0]->firstname,
'email' => $result[0]->email,
'id' => $result[0]->id,
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->load->view("user_include/header");
$this->load->view('user_site/index');
}
} else {
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('user_site/login_form', $data);
}
}
}
// Logout
public function logout() {
// Removing session data
$sess_array = array(
'email' => ''
);
$this->session->unset_userdata('logged_in', $sess_array);
$data['message_display'] = 'Successfully Logout';
$this->load->view('user_site/login_form', $data);
}
}
?>
model
// Read data using username and password
public function login($data) {
$condition = "email =" . "'" . $data['email'] . "' AND " . "password =" . "'" . $data['password'] . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}
// Read data from database to show data in admin page
public function read_user_information($email) {
$condition = "email =" . "'" . $email . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
}
?>
view
<?php
if (isset($this->session->userdata['logged_in'])) {
$firstname = ($this->session->userdata['logged_in']['firstname']);
$email = ($this->session->userdata['logged_in']['email']);
$id = ($this->session->userdata['logged_in']['id']);
} else {
header("location: login");
}
the error is in you user_include/header.php , check the id and firstname are set before you echo them out.
In your model replace following code by given code:
public function read_user_information($email) {
$condition = "email =" . "'" . $email . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
To
public function read_user_information($email) {
$this->db->select('firstname, email, id');
$this->db->from('user');
$this->db->where('email',$email);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->row_array();
} else {
return false;
}
}
In your controller replace following code by given
$email = $this->input->post('email');
$result = $this->login_database->read_user_information($email);
if ($result != false) {
$session_data = array(
'firstname' => $result[0]->firstname,
'email' => $result[0]->email,
'id' => $result[0]->id,
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->load->view("user_include/header");
$this->load->view('user_site/index');
}
To
$email = $this->input->post('email');
$user_details = $this->login_database->read_user_information($email);
if ($user_details != false) {
// Add user data in session
$this->session->set_userdata('logged_in', $user_details);
$this->load->view("user_include/header");
$this->load->view('user_site/index');
}
In view, replace your code by following:
<?php
$user_details = $this->session->userdata['logged_in']);
if ($user_details != "") {
$firstname = $user_details['firstname'];
$email = $user_details['email'];
$id = $user_details['id'];
} else {
header("location: login");
}

change password in codeigniter

Hi i write code for change password but it does not change the password in table
but make 0 current password.So what i do.Thanks
THis is my Model
function changepassword() {
$this->db->select('id');
$this->db->where('username', $this->session->userdata('username'));
$this->db->where('password', $this->input->post('OldPassword'));
$query = $this->db->get('mau_user');
if ($query->num_rows() > 0) {
$row = $query->row();
if ($row->id === $this->session->userdata('id')) {
$data = array(
'password' => $this->input->post('password')
);
$this->db->where('username', $this->session->userdata('username'));
$this->db->where('password', $this->input->post('OldPassword'));
if ($this->db->update('mau_user', $data)) {
return "Password Changed Successfully";
If in the db the field password is set as an integer, the default value is 0, so probably the value you're tryn' to update it's invalid, you should print the SQL and start debuggin from there....
in controller
function edit_password()
{
$uderid = $this->session->userdata('user_id');
// update data
if($_POST)
{
if($this->input->post('old_password')!=''){
$this->form_validation->set_rules('old_password','Old password', 'trim|required|xss_clean|addslashes|encode_php_tags |callback_oldpass_check');
$this->form_validation->set_rules('new_password','New password', 'trim|required|xss_clean|addslashes|encode_php_tags|min_length['.PASS_MIN_LEN.']|md5');
$this->form_validation->set_rules('conf_password', 'Confirm password', 'trim|required|xss_clean|addslashes|encode_php_tags|min_length['.PASS_MIN_LEN.']|matches[new_password]|md5');
if($this->form_validation->run() == TRUE)
{
$data =array( 'password' => $this->input->post('conf_password'));
$this->main->update('users','user_id',$uderid,$data);
$this->change_password('Password updated successfully');
}
else{
$this->change_password();
}
}
else{
redirect(base_url().'user' , '301');
}
}
}
function oldpass_check($oldpass)
{
$user_id = $this->session->userdata('user_id');
$result = $this->main->check_oldpassword($oldpass,$user_id);
if($result ==0)
{
$this->form_validation->set_message('oldpass_check', "%s doesn't match.");
return FALSE ;
}
else
{
return TRUE ;
}
}
Model
function check_oldpassword($oldpass,$user_id)
{
$this->db->where('user_id', $user_id);
$this->db->where('password', md5($oldpass));
$query = $this->db->get('users'); //data table
return $query->num_rows();
}

Categories