passing user information to view in codeigniter - php

I am trying to get users details from the database and put it in session so that it can be used in the view. I have tried all I can but I keep getting error. Undefined Variable Email.
MODEL:
function login($username, $password)
{
$this->db->select('authTbl.id, authTbl.password, authTbl.username, authTbl.email, authTbl.mobile');
$this->db->from('users as authTbl');
$this->db->where('authTbl.username', $username);
$this->db->where('authTbl.isDeleted', 0);
$query = $this->db->get();
$user = $query->result();
if(!empty($user)){
if(verifyHashedPassword($password, $user[0]->password)){
return $user;
} else {
return array();
}
} else {
return array();
}
}
CONTROLLER:
function isLoggedIn()
{
$isLoggedIn = $this->session->userdata('isLoggedIn');
$data['title'] = 'Login';
if(!isset($isLoggedIn) || $isLoggedIn != TRUE)
{
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
}
else
{
redirect('posts');
}
}
/**
* This function used to logged in user
*/
public function login()
{
$this->load->library('form_validation');
$data['title'] = 'Login';
$this->form_validation->set_rules('username', 'Username', 'required|max_length[128]|trim');
//$this->form_validation->set_rules('password', 'Password', 'required|max_length[32]|');
if($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
}
else
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$result = $this->user_model->login($username, $password);
if(count($result) > 0)
{
foreach ($result as $res)
{
$sessionArray = array('id'=>$res->id,
'username'=>$res->username,
'email'=>$res->email,
'mobile'=>$res->mobile,
'isLoggedIn' => TRUE
);
$this->session->set_userdata($sessionArray);
$this->session->set_flashdata('user_login', 'Welcome');
redirect('posts');
}
}
else
{
$this->session->set_flashdata('login_fail', 'Email or password mismatch');
redirect('users/login');
}
}
}
VIEW:
<?php echo $email; ?>

You are creating the session for user information
Try to fetch the session data :
echo $this->session->userdata('email');
or trying to pass the data in views $data

$email will not work because writing $email means ordinary variable but in your case you have to write like :
<?php echo $this->session->userdata('email'); ?>

If You are using flashdata, then You can get it using below code:
Controller
if (empty($this->session->userdata('UserID'))) {
$this->session->set_flashdata('flash_data', 'You don\'t have access!');
$this->load->view("initialHeader");
$this->load->view("login");
redirect('Login');
}
View
<?php if(!empty($this->session->flashdata('flash_data'))) {
?>
<div class="alert alert-danger">
<?php echo $this->session->flashdata('flash_data'); ?>
</div>
<?php } ?>
If You are using tmp data as a session, please refer below code:
Controller
<?php
if (!empty($data)) {
$this->session->set_userdata('permission_error_msg', $data);
$this->session->mark_as_temp('permission_error_msg', 10); // For 10 Seconds
$this->load->view('dashboard', array($title, $data));
} ?>
View
<?php if ($this->session->tempdata('permission_error_msg')) { ?>
<b class="login_error_msg"><?php
if (!empty($this->session->tempdata('permission_error_msg'))) {
echo $this->session->tempdata('permission_error_msg');
}
?></b>
<?php } ?>
Thank You.

Related

login form submit results in authentication failed in codeigniter 3.1.2

my validations are working ok but after that userid and password results empty in model fit_reg_model and it results into authentication failed.please help me out.
this is my code :
model fit_reg_model
`
class Ftg_reg_model extends CI_Model {
public function log_valid( $userid, $password )
{
$this->db->select("regID,loginCode");
$whereCondition = $array = array('regID' =>$userid,'loginCode'=>$password);
$this->db->where($whereCondition);
$this->db->from('fit_1login');
$query = $this->db->get();
////////////////////////////////checking values////////////////////
echo"<pre>";
print_r ($query->result()); exit;
return $query->row()->countID;
if( $query->num_rows() )
{
echo"<pre>";
print_r ($query->result()); exit;
return $query->row()->countID;
//return TRUE;
}
else
{
return FALSE;
}
}
}
contrller fit_ci
` public function fit_loguser()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('uname','User Id','required|valid_email|valid_emails|trim');
$this->form_validation->set_rules('password','Password','required|trim');
$this->form_validation->set_error_delimiters("","");
if($this->form_validation->run() )
{
$userid = $this->input->post('uname');
$password = $this->input->post('password');
//////////////////////////////////////loding model////////////////
$this->load->model('ftg_reg_model');
//echo $userid , $password;
if( $this->ftg_reg_model->log_valid('$userid','$password')== True )
{
//$this->load->view('fitasy/fit_userprofile');
$this->load->library('session');
$this->session->set_userdata('id',$id);
echo "Successful loged";
}
else
{
echo "Authentication failed";
}
}
else
{
$data['title'] = 'Fit';
$this->load->helper('form');
$this->load->view('fit/index.php',$data);
}
}
`
view fit_loguser
`
Login here to add items to your Cart
'form-horizontal'])?>
<?php echo form_error('uname'); ?>
<?php echo form_input(['name'=>'uname','class'=>'form-control','placeholder'=>'Username','value'=>set_value('uname')])?><br>
<?php echo form_error('password'); ?>
<?php echo form_password(['name'=>'password','class'=>'form-control','placeholder'=>'Password'])?><br>
<?php echo form_submit(['name'=>'logsubmit','class'=>'btn btn-default','value'=>'Proceed','type'=>'submit'])?>
<?php echo form_close()?><!-------------form close-------------------------------------->
</div>`
Try to remove
$this->db->select("regID,loginCode");
In your model to see what's happening

How to retrieve a single user data that is owned by the user who log in using session in CodeIgniter?

I'm new to CodeIgniter. My problem with my code is that, when a user logged in to his/her account, he can't view his/her details, instead, the detail of the first row from the table where I fetched it. I tried all of the accounts, but still the first row will show.
My goal is, when a user can log in, he will be redirected to his account with his details.
Controller
public function __construct()
{
parent::__construct();
$this->load->model('My_profile_model');
if(!$this->session->userdata('logged_in'))
{
// Set error
$this->session->set_flashdata('need_login', 'Sorry, you need to be logged in to view that area');
redirect('home/index');
}
}
public function show($teachers_id)
{
$user_id = $this->session->userdata('user_id');
$data['my_data'] = $this->My_profile_model->get_my_profile($teachers_id);
$data['title'] ='My Profile';
$data['nav_content'] = 'layouts/teacher_nav';
$data['main_content'] = 'teachers/my_profile';
$this->load->view('layouts/main', $data);
}
Model
<?php
class My_profile_model extends CI_Model{
public function get_my_profile($teachers_id)
{
$query = $this->db->get('teachers');
$this->db->where('teachers_id',$teachers_id);
return $query->row();
}
}
View
<h2 class="featurette-heading"><?php echo $my_data->first_name; ?> <?php echo $my_data->last_name; ?> <BR /><span class="text-muted"><?php echo $my_data->rank_id; ?></span></h2>
<hr>
<h4><small>Gender:</small> <?php echo $my_data->gender; ?></h4>
<h4><small>Status:</small> <?php echo $my_data->status; ?></h4>
<h4><small>Address:</small> <?php echo $my_data->address_id; ?></h4>
<h4><small>Field of Specialization:</small> <?php echo $my_data->fos_id; ?></h4>
<h4><small>School Graduated:</small> <?php echo $my_data->school_graduated; ?></h4>
<h4><small>Eligibility:</small> <?php echo $my_data->eligibilities; ?></h4>
<h3>Educational Qualification</h3>
<h4><small>Bachelors Degree:</small> <?php echo $my_data->bachelors_degree; ?></h4>
<h4><small>Masteral (Unit):</small> <?php echo $my_data->m_unit; ?></h4>
<h4><small>Years of Teaching Experience:</small> <?php echo $my_data->years_of_teaching; ?></h4>
Here, I will also include my login controller because I'm not sure if this controller returns a session.
users Controller
public function login()
{
$this->form_validation->set_rules('username','username','trim|required|min_length[4]|xss_clean');
$this->form_validation->set_rules('password','password','trim|required|min_length[4]|max_length[50]|xss_clean');
if($this->form_validation->run() == FALSE)
{
redirect('home');
}
else
{
//Get from post
$username = $this->input->post('username');
$password = $this->input->post('password');
$level = $this->input->post('level');
//Get user id from model
$user_id = $this->User_model->login_user($username, $password, 1, $level);
//Validate user
if($user_id <> 0)
{
//Create array of user data
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'level' => $level,
'logged_in' => TRUE
);
//Set session userdata
$this->session->set_userdata($user_data);
if ($level === 'Administrator') {
$this->session->set_flashdata('login_success', 'You are now logged in as an administrator');
redirect('admin/profiles');
}
if ($level === 'Teacher') {
$this->session->set_flashdata('login_success', 'You are now logged in as a teacher');
redirect('teacher/my_profile');
}
}
else
{
//Set error
$this->session->set_flashdata('login_failed', 'The login info that you entred is invalid. Please try again.');
redirect('home/index');
}
}
}
And the model for user controller
public function login_user($username, $password, $status, $level)
{
//Validate
$this->db->select('*');
$this->db->from('users');
$this->db->where('username', $username);
$this->db->where('password', $password);
$this->db->where('status', $status);
$this->db->where('level', $level);
$result = $this->db->get();
if ($result->num_rows() == 1){
return $result->row(0)->teachers_id;
}
}
As I've said, I'm new to this. Any help will be appreciated.
Thanks in advance :)
Oh, got the answer now..
I just change the query of my model
public function get_my_profile($teachers_id = NULL)
{
$user_id = $this->session->userdata('user_id');
$this->db->select('*');
$this->db->from('teachers');
$this->db->join('users','users.teachers_id = teachers.teachers_id');
$this->db->where('users.teachers_id',$user_id);
$query = $this->db->get();
return $query->row();
}

How can i make a reset password function in codeigniter?

Whenever i run this code, i recieve a blank screen on submission. The code does not seem to work and i'm unsure why. Can anyone see an issue? I've checked it for syntax already mutliple times.
Controller:
public function changepwd(){
$this->form_validation->set_rules('oldpassword','Old Password','required|trim|xss_clean|callback_change');
$this->form_validation->set_rules('password1','New Password','required|trim');
$this->form_validation->set_rules('password2','Confirm Password','required|trim|matches[password1]');
if($this->form_validation->run()= true){
redirect('admin');
}else{
$this->form_validation->set_message('change','info is wrong');
redirect('admin');
}
}
public function change(){
$this->load->view('error_display');
$oldpass = $this->input->post('oldpassword');
if(isset($oldpass)){
if($this->input->post('password1') == $this->input->post('password2')){
$session=$this->session->userdata("logged_in");
$username= $session['username'];
$query = "SELECT * FROM database where username='$username'";
$result = $this->db->query($query);
$row=$result->row();
$pass = $row->password;
$s= $row->salt;
$user_old_pass = sha1($s.$oldpass);
if($pass == $user_old_pass){
$new = substr(uniqid(rand(), true), 0, 20);
$users_password = $this->input->post('pass1');
$new_password = sha1($new.$user_password);
$data = array($new,$new_password);
$this->update_model->insert_model($data);
$this->form_validation->set_message('change','saved');
$this->load->view('admin');
}else{
$this->form_validation->set_message('change','<p class="error">Incorrect Password</p>');
return false;
redirect('admin');
}
}else{
$this->form_validation->set_message('change','passwords dont match');
return false;
redirect('admin');
};
}else{
$this->form_validation->set_message('change','old password is not entered');
return false;
redirect('admin');
}
model:
function login($data)
{
$this->db->update('database', $data);
}
your
if($this->form_validation->run()= true){
should be
if($this->form_validation->run() == FALSE) {
because you are redirecting every time to 'admin'

Login section not working well in php codeigniter

I'm using php codeigniter for my project. In my login page if username and password is invalid just load the login page, else load the home. if invalid, First time it loads the login page again given the wrong details for login one controller name is added in url like local turns like localhost/project name/administrator/administrator/login_authentication
my code is
function index()
{
if($this->session->userdata('usertype') != '')
{
redirect('administrator/administrator_view');
}
else
{
$this->load->view('login');
}
}
function login_authentication()
{
$username=$this->input->post('username');
$password=$this->input->post('password');
$user = $this->administrator->admin_authentication($username,$password);
if(count($user) == 1)
{
foreach($user as $admin_value)
{
$user_name=$admin_value['UserName'];
$usertype=$admin_value['UserType'];
}
$session_data = array(
'username' => $user_name,
'usertype' => $usertype,
);
$this->session->set_userdata($session_data);
if($usertype == 1)
{
redirect('administrator/administrator_view');
}
}
else
{
$data['Invalid_Login']="Invalid Username and Password";
$this->load->view('login',$data);
}
}
function administrator_view()
{
if($this->session->userdata('usertype') == '')
{
redirect('administrator');
}
else
{
$data['heading'] = '';
$this->load->view('header', $data);
$this->load->view('dashboard', $data);
$this->load->view('footer');
}
}
Admin authentication function
function admin_authentication($username, $password)
{
$this->db->select('*');
$this->db->from('user');
$this->db->where('UserName',$username);
$this->db->where('Password',$password);
$query = $this->db->get();
return $query->result_array();
}
I'm trying more than one time given not correct information for login everytime one controller name added in url. Please help me.
Thanks in advance.
change
$this->session->set_userdata($session_data);
to
$this->session->set_userdata(('some_name', $session_data);
and change
if($this->session->userdata('usertype') == '')
in all area to
$ses = $this->session->userdata('some_name');
if($ses['usertype'] == '')
and try....
first of all check if there is an post request in your function login_authentication() like this:
function login_authentication()
{
if( $this->input->post(null) ){
//your authentication code here
}else{
//load the login view here
}
}
Here is your function:
function login_authentication(){
if( $this->input->post(null) ){ //check if there is an post request
$username=$this->input->post('username');
$password=$this->input->post('password');
$user = $this->administrator->admin_authentication($username,$password);
print_r( $user );die(); //the user array as returned from the model see if its correct or not
if(count($user) == 1)
{
foreach($user as $admin_value)
{
$user_name=$admin_value['UserName'];
$usertype=$admin_value['UserType'];
}
$session_data = array(
'username' => $user_name,
'usertype' => $usertype,
);
print_r( $session_data );die; //see if it builds the correct array or not
//$this->session->set_userdata($session_data);
$this->session->set_userdata('user_info',$session_data); //to read the username use like $this->session->userdata['user_info']['username'];
if($usertype == 1)
{
redirect('administrator/administrator_view');
}
}else{ //invalid credentials load the login view
$this->session->set_flashdata('Invalid_Login', 'Invalid username or password!'); //to echo in view use $this->session->flashdata('Invalid_Login');
redirect('administrator', 'refresh');
}
}else{ //redirect to index function now
redirect('administrator', 'refresh');
}
}
In your function administrator_view(),
function administrator_view(){
if( !$this->session->userdata('user_info') ){
print_r( $this->session->all_userdata() );die('no session set redirecting'); //the session is not set here
redirect('administrator');
}
else{
$data['heading'] = '';
$this->load->view('header', $data);
$this->load->view('dashboard', $data);
$this->load->view('footer');
}
}

The alert message is displaying without the login form

In the below codeigniter code i have placed the controller and view part.Now if a inactive tries to log the account it should display in active user along with login form .In my case the message is displaying without login and finally login forms disappear.
Controller:
function index()
{
$data['main_content'] = 'login_form';
$this->load->view('includes/template', $data);
}
function inactive()
{
echo"<script>alert('In active user');</script>";
}
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->inactive(); }
}
else // incorrect username or password
{
$this->index();
}
}
view:
<?php $this->load->view('includes/header'); ?>
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>css/style1.css" />
<div id="login_form">
<h1>Login!</h1>
<?php
echo form_open('login/validate_credentials');
echo form_input('username', 'Username');
echo form_password('password', 'Password');
echo form_submit('submit', 'Login');
echo anchor('login/signup', 'Create Account');
echo form_close();
?>
</div><!-- end login_form-->
<?php $this->load->view('includes/footer'); ?>
I can't see where ve you called your view file in inactive() in controller??
function inactive()
{
echo"<script>alert('In active user');</script>";
$this->load->view('Your view with login form'); // this part
}
The most obvious (possible) mistake here is that you do not pass your posted data to $this->membership_model->validate();. Since you did not post the code to that function I can not be 100% sure, but I am willing to bet that this is the problem. The information is not passed, so the $query variable is not properly set, hence the error displays.
Why don't you try this:
function index($inactive_login = FALSE) {
$data['inactive_login'] = $inactive_login;
$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
);
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
{
$inactive_login = TRUE;
$this->index($inactive_login);
}
}
else // incorrect username or password
{
$this->index();
}
}
View:
<?php $this->load->view('includes/header'); ?>
<?php
if($inactive_login){
echo "<script>alert('In active user');</script>";
}
?>
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>css/style1.css" />
<div id="login_form">
<h1>Login!</h1>
<?php
echo form_open('login/validate_credentials');
echo form_input('username', 'Username');
echo form_password('password', 'Password');
echo form_submit('submit', 'Login');
echo anchor('login/signup', 'Create Account');
echo form_close();
?>
</div><!-- end login_form-->
<?php $this->load->view('includes/footer'); ?>

Categories