Hi guys I have a User controller and User_model model. I want to be able to retrieve and display a logged in users email and phone number from the database to a view after the user is logged in. any idea how I could go about this would be appreciated and if codes could be written to demonstrate I would be very happy.
MODEL
public function login($username, $password){
//validation
$this->db->select('id, email, username');
$this->db->where('username', $username);
$this->db->where('password', $password);
$this->db->where('status', 1);
$result = $this->db->get('users');
if($result->num_rows() == 1){
return $result->row(0)->id;
} else {
return FALSE;
}
}
public function get_user($username){
$this->db->where('username', $username);
$query = $this->db->get('users');
return $query->result();
}
CONTROLLER:
public function login(){
$data['title'] = 'Login';
$this->form_validation-> set_rules('username', 'Username', 'required');
$this->form_validation-> set_rules('password', 'Password', 'required');
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
} else {
// fetching user
$username = $this->input->post('username');
//Encrypted password
$password = md5($this->input->post('password'));
//login user
$user_id = $this->user_model->login($username, $password);
if($user_id){
//creating session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => TRUE,
);
$this->session->set_userdata('user_data',$user_data);
// Set message to be sent
$this->session->set_flashdata('user_login', 'Welcome');
redirect('posts');
} else {
// Set message to be sent
$this->session->set_flashdata('login_fail', 'Login Failed');
redirect('users/login');
}
}
}
public function get_user()
{
if($this->session->userdata('logged_in')){
$username = $this->session->userdata('username');
$data['results'] = $this->user_model->get_user($username);
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
}
}
There is basic problem in your Controller
Session Data Problem: In your Controller you storing all array data in CodeIgniter Session:
the 'user_data' would work like array key, and all other array will be assign as keys data;
$this->session->set_userdata('user_data', $user_data);
and you retrieving/checking the session data by using $this->session->userdata('logged_in') and $this->session->userdata('username'), It's wrong my friend. You can get user data session by $this->session->userdata('user_data')['username'] or $this->session->userdata['user_data']['username'] ...
Because the session would be like;
Array
(
[__ci_last_regenerate] => 1499791562
// This is the array key 'user_data' where your array data stores
[user_data] => Array
(
[user_id] => 1
[username] => scott
[email] => scott.dimon#example.com
[phone_number] => 1234567890
[first_name] => Scott
[logged_in] => 1
)
)
So, you have to have use 'user_data' with session to get your data
One thing I would like to share with everyone, Always Read The Docs and manual Carefully. Believe me if you read before the start, your code would be more nicer and cleaner... Ha ha ha ha ha.. ;) :|
When you login if you set the users_id in session you can get the information like
Read manual also
https://www.codeigniter.com/user_guide/database/results.html#result-rows
https://www.codeigniter.com/user_guide/general/views.html#adding-dynamic-data-to-the-view
Make sure you autoload session, and database.
Examples ONLY below.
Filename: User_model.php
class User_model extends CI_Model {
public function get_user($id)
{
$this->db->where('user_id', $id);
$user_query = $this->db->get('yourtable');
return $user_query->row_array();
}
}
Filename: Dashboard.php
Controller
<?php
class Dashboard extends CI_Controller {
public function __construct()
{
parent::__construct();
if (!$this->session->userdata('user_id'))
{
redirect('logoutcontroller');
}
$this->load->model('user_model');
}
public function index()
{
$userdata = $this->user_model->get_user($this->session->userdata('user_id'));
/** You can use what you want example
$data['email'] = $userdata['email'];
**/
$data['username'] = $userdata['username'];
$this->load->view('some_view', $data);
}
}
View
<?php echo $username;?>
You can use session to carry the logged in user detail.
This is your model code:
//In your model
$query = $this->db
->select('id,email,phone')
->where(['username' => $username, 'password' => $password])
->where('status','1')
->get('users');
$user_data = $query->row_array();
if (!empty($user_data)) {
return $user_data;
} else {
return FALSE;
}
In side the controller where you get the user data if username & password is correct. Here you can put the user data on session:
//In Side Controller
$user_data = $this->user_model->login($username, $password);
if(isset($user_data) && !empty($user_data)){
// you can directly add the `$user_data` to the session as given billow.
// set user data in session
$this->session->set_userdata('user_data', $user_data);
Now after putting a data on session you can retrive it any where, on any view or in side morel, controller.
//retrive the user data in any view
//To echo in view Inside your view code.
<?php
$session_data = $this->session->userdata('user_data');
$user_email = $session_data['email'];
$user_phone = $session_data['phone'];
$user_id = $session_data['id'];
?>
<?= $user_phone ?> OR <?php echo $user_phone; ?>
<?= $user_email ?> OR <?php echo $user_email; ?>
On Your $this->load->view('users/login', $data); this view. Where the HTML & PHP code placed.
Example:
<html>
// Your View Page
</body>
<?php
$session_data = $this->session->userdata('user_data');
$user_email = $session_data['email'];
$user_phone = $session_data['phone'];
$user_id = $session_data['id'];
?>
<h1> Logged In User Email: <?= $user_email ?> </h1>
<h1> Logged In User Phone: <?= $user_phone ?> </h1>
<body>
</html>
Note: Once You save the user data inside the session then you don't need to pass that data to the view form controller. You just need to echo it where you need that.
You need to load session library first. like
$this->load->library('session');
Then after you can save your data into session like,
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
Then where ever you require at controller you can retrive session data like,
$data['session_data'] = $this->session->all_userdata();
and then pass to your view,
$this->load->view('data', $data);
and then access that data into your view with the key,
<?= $session_data['username']; ?>
I hope it helps,
Does this answer your question?
public function login($username, $password){
$db = $this->db;
//validation
$db->select('id, email, username');
$db->where('username', $username);
$db->where('password', $password);
$db->where('status', 1);
$result = $db->get('users')->row_array();
return empty($result['id']) ? false : $result['id'];
}
With a unique index on username you won't need to check the number of rows as it will be limited to 1.
if($user_id){
//creating session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => TRUE,
);
$this->session->set_userdata($user_data);
// Set message to be sent
$data['session_data'] = $this->session->all_userdata();
$this->session->set_flashdata('user_login', 'Welcome');
$this->load->view('posts', $data);
//redirect('posts');
}
else {
// Set message to be sent
$this->session->set_flashdata('login_fail', 'Login Failed');
redirect('users/login');
}
}
at the view,
<?php print_r($session_data); ?>
if you get your session data into print,
you can display it like,
<?= $session_data['user_id']; ?>
****Modal**
//user login**
function userlogin($data)
{
$condition = "username =" . "'" . $data['username'] . "' AND " . "password =" . "'" . $data['password'] . "' AND " . "status = '1'";
$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;
}
}
And in your Controller check
if($this->modal_name->login()==false)
{
//redirect user to login page
}
else
{
$data['details'] = $this->modal_name->login();
$this->load->view("post",$data);
}
View
foreach($details as $detail)
{
echo $detail->id;
echo $detail->username;
}
Related
I am having a trouble on displaying my admin's full name, like for example admin full name is John Doe, it is not displaying. I am still learning codeigniter please give me advice thank you!
here is my controller
//Get username
$username = $this->input->post('username');
//Get and encrypt the password
$password = $this->input->post('password');
// Login user
$user_id = $this->role_model->login($username, $password);
if ($user_id) {
// Create session
$user_data = array(
'user_id' => $user_id,
'name' => $user_id->name,
'username' => $username,
'logged_in' => true
);
$this->session->set_userdata($user_data);
//Set message
$this->session->set_flashdata('user_loggedin','You are now logged in');
redirect('pages/index');
here is my View - where I would like to display my full name, as you can see 'name' is the data field I have to display but it is does not show anything, it gives an error that says name is not defined.
<li><a> Welcome, <?php echo $this->session->name ?> </a></li>
Model
public function login($username, $password){
//Validate
$this->db->where('username',$username);
$this->db->where('password',$password);
$result = $this->db->get('users');
if ($result->num_rows() == 1) {
return $result->row(0)->id;
}else{
return false;
}
}
Your method login() returns only id = digit (return $result->row(0)->id;), not object (in controller your get $user_id->name).
Do this, in the model:
if ($result->num_rows() == 1) {
return $result->row(0); // fix
}else{
return false;
}
In the controller:
$user = $this->role_model->login($username, $password);
$user_data = array(
'user_id' => $user->id, // fix
'name' => $user->name, // fix
'username' => $username,
'logged_in' => true
);
It shows undefined because it is indeed undefined.
In your view your're trying to echo the returning value of a function called userdata(), does that function actually exist? Or is $this->session->userdata an array? in which that case, you need to use [ index ] to acces a member within an array. i.e. $this->session->userdata['name'], but also, that member needs to exist first.
controller :
if($this->Login_model->login_valid($email,$password))
{
$sessiondata = array(
'username' => $email
);
$this->session->set_userdata('logged_in', $sessiondata);
redirect('narson');
}
else
{
$this->session->set_flashdata('error',"Invalid Username And password");
redirect('login');
}
model:
public function login_valid($username,$password)
{
$this->db->where('username',$username);
$this->db->where('password',$password);
$query = $this->db->get('admin');
if($query->num_rows() > 0)
{
return true;
}
else
{
return false;
}
}
I have the following error in my code:
1) the data i am storing over session is not showing up in view
2) the form validation set rules is not working.. The required is not working. Whenever i press login without entering any field it prints a.
I have auto loaded session and form validation.
Should I use php sessions or ci sessions?
Controller:
public function loginFormValidation()
{
$this->form_validation->set_rules('email','Username','required'); //not working
$this->form_validation->set_rules('pass','Password','required');
$this->form_validation->set_error_delimiters('<div class = "text-danger">', '</div>');
if($this->form_validation->run())
{
$email = $this->input->post('email');
$pass = $this->input->post('pass');
$this->load->model('loginModel');
$result = $this->loginModel->loginValidation($email,$pass);
$user_id = $result->user_id;
$user_name = $result->user_name;
$password = $result->password;
$arrayDb = array(
'user_id' => $user_id,
'user_name' => $user_name,
'password' => $password,
);
$this->session->set_userdata('row', $arrayDb);
header("location:".base_url()."/Users/dashboard");
}
else
{
echo "a";
}
}
Model:
class loginModel extends CI_Model
{
public function loginValidation($email,$pass)
{
$q = $this->db->where(['email' => $email, 'password' => $pass])
->get('users');
if($q->num_rows())
{
return $q->row();
}
else
{
return false;
}
}
}
Controller where i am printing it for testing:
class Users extends CI_Controller
{
public function dashboard()
{
echo $this->session->userdata('user_name'); // Empty no data showing
exit;
}
}
Your code has a few errors and oversights.
You should NEVER store plaintext passwords, let alone add them to a session variable. There is no need for that. Check out: http://php.net/manual/en/function.password-verify.php
You need to check whether or not the login function actually returned data, otherwise just anyone can "login" as long as they pass form validation.
You are setting session data with an array incorrectly according to the way you want to access the variables.
Controller:
public function loginFormValidation() {
$this->form_validation->set_rules('email', 'Username', 'required');
$this->form_validation->set_rules('pass', 'Password', 'required');
$this->form_validation->set_error_delimiters('<div class = "text-danger">', '</div>');
if ($this->form_validation->run()) {
$email = $this->input->post('email');
$pass = $this->input->post('pass'); // do not store plaintext!!!
$this->load->model('loginModel');
$result = $this->loginModel->loginValidation($email, $pass);
if ($result) {
$user_id = $result->user_id;
$user_name = $result->user_name;
$password = $result->password;
//https://www.codeigniter.com/user_guide/libraries/sessions.html#adding-session-data
$arrayDb = array(
'user_id' => $user_id,
'user_name' => $user_name,
'password' => $password, // why are you storing their PLAINTEXT password in a session?!
);
$this->session->set_userdata($arrayDb);
header("location:" . base_url() . "/Users/dashboard");
} else {
echo 'login failed; bad username/password.';
}
} else {
echo validation_errors();
}
}
Model:
public function loginValidation($email, $pass) {
$q = $this->db->where(['email' => $email, 'password' => $pass])
->get('users');
if ($q->num_rows() == 1) {
return $q->row();
}
return false;
}
Rather than reinventing the wheel check out: https://github.com/benedmunds/CodeIgniter-Ion-Auth
I personally use it an recommend it.
I'm creating a session at login but it's not saving the variables I store inside the session nor is it carrying them across to other pages:
Controller code:
function CheckDatabase($password) //This function is only run when password validation is correct.//
{
$username = $this->input->post('Username'); //Sets the username as a $username.//
$result = $this->User_model->Login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array( //Makes an array of the data to be stored in the session.//
'UserID' => $row->UserID,
'Username' => $row->Username
);
$this->session->set_userdata('logged_in', $sess_array); //Sets $sess_array as the session.//
}
return TRUE;
}
else //Ran if the username or password aren't matched in the CIUsers database. Returns error message.//
{
$this->form_validation->set_message('CheckDatabase', 'Invalid login details.');
return false;
}
}
Index function on the same controller (which should stop a user going back to the login screen but doesn't)
function index() //Default function that is run when this controller is called.//
{
if($this->session->userdata('logged_in'))
{
redirect('Home_controller');
}
else
{
$this->load->helper(array('form'));
$this->load->view('Login_view');
}
}
Code on the home view (which browser is directed to once logged in)
<?php echo $UserID .": ".$Username; ?>
I get this error for displaying the session data:
Message: Undefined variable: Username
Filename: views/Home_view.php
Line Number: 9
To retrieve the session variable, you have to do like this
$username = $this->session->userdata['logged_in']['Username'];
echo $username;
You have to retrieve it from session like this before using:
$user = $this->session->userdata('logged_in');
$Username = $user['Username'];
$UserID = $user['UserID'];
Try like this
$newdata = array(
'user_id' => $rows->id,
'user_name' => $rows->name,
'user_image' => $rows->user_image,
'user_email' => $rows->email,
'logged_in' => TRUE,
'user_type' => $rows->user_type
);
}
$this->session->set_userdata($newdata);
And check in your controller construct for user session
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class User extends CI_Controller {
public function __construct() {
parent::__construct();
//Here we will check for the session value if it is true then the function will run else it will redirect to login page
if ($this->session->userdata('logged_in') == FALSE) {
redirect(site_url('your login page'));
} else {
// if there is session value
redirect(site_url('User/your function name');
}
}
}
?>
For complete explaination read this tutorial
http://w3code.in/2015/10/session-handling-in-codeigniter/
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array( //Makes an array of the data to be stored in the session.//
'UserID' => $row[0]->UserID,
'Username' => $row[0]->Username
);
$this->session->set_userdata('logged_in', $sess_array); //Sets $sess_array as the session.//
}
return TRUE;
}
I'm trying to make a login using sessions in codeigniter at the time the username and password match, but I can't get it. I'm doing this:
Controller:
public function __construct()
{
parent::__construct();
$this->load->model('main_select');
$this->load->helper('url');
$this->load->library('session');
}
...code when username and password match:
if($pass === $user){
$this->session->set_userdata(array(
'user_id' => $login['id_user'],
));//we create the session 'user_id'
}
here it is supposed that we created a session called 'user_id'
in the view it doesn't work, I have this:
if( !$this->session->userdata('id_user') ){
//see this content
//first content
}else{
//see this other
//second content
}
but I always see the same content('second content').
trying to destroy it (but not working):
public function logout()
{
//session_unset();
// destroy the session
//session_destroy();
$this->session->unset_userdata('id_user');
header("Location: ".base_url() );
}
what am I doing wrong? thanks
EDIT1:
$password = md5( $this->input->post('inputpassword') );
$login = $this->login_select->get_username($username);
//si no coincide
if( $login['password'] !== $password ) {}
Note : Always use database to handle user logins. (Code is related to database login check)
in your database create table with user and add this 2 fields.
username
password
Add some user logins to it
Then in your code
public function __construct()
{
parent::__construct();
$this->load->model('main_select');
$this->load->helper('url');
$this->load->library('session');
}
// logging
public function loging()
{
$user = mysql_real_escape_string($_POST['username']);
$pass = md5(mysql_real_escape_string($_POST['password']));
$validate = $this->main_select->validate_user($user,$pass);
if(empty($validate) || $validate>1)
{
//Not a valid user
//redirect to login page
$this->load->view('loging');
}
else
{
//valid user
//set the session
$array = array('user_id' => '$user');
$this->session->set_userdata();
//redirect to normal page
$this->load->view('home_page');
}
}
//logout
public function logout()
{
$result= $this->session->sess_destroy();
if ((isset($result)))
{
header("Location: ".base_url() );
}
else
{
}
}
In Model
public function validate_user($user,$pass)
{
$query = $this->db->query("SELECT * FROM user WHERE username= '$user' AND password='$pass'");
$result = $query->result_array();
$count = count($result);
return $count;
}
modify this line of changes then your script will work as id_user need to set first to use in script.
if($pass === $login['password'] && $user===$login['username']){
$this->session->set_userdata(array(
'id_user' => $login['id_user'],
));//we create the session 'user_id'
}
here $login['password'] and $login['username'] are data come from tables and need to change fieldname pass or user according to your user table.
Hi i have created a session in Codeigniter i have set the session variable in my model. But after setting the session variable value when i call session variable in my view through Controller the session variable value becomes null. Any help???
Update
This is my Model where i set my session variable
function login ($username, $password)
{
$this->db->where('username' , $username);
$this->db->where('password', $password);
$query = $this->db->get('users');
if ($query->num_rows()>0)
{
foreach ($query->result() as $rows)
{
$data = array(
'user_name' => $rows->username,
'logged_in' => TRUE,
'validated' => true
);
}
$this->session->set_userdata($data);
//$user = $rows->username;
//$this->session->set_userdata('user_name', $user);
return true;
}
else
{
return false;
}
}
Here is my controller from where i redirect to the view
public function verification()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$result = $this->site_model->login($username, $password);
//$result = $this->session->set_userdata('validated');
if ($result)
{
//$this->admin();
//$this->session->set_userdata('login_state', TRUE);
redirect ('site/index');
}
else
{
redirect ('site/login');
//$this->load->view('login');
}
}
i have called the session_start(); in controller under construct();
and this is how i access the session variable in my view
<?php if ($this->session->userdata('user_name') != "") { ?>
.....
First of All in CI you don't need to use session_start() anywhere. only autoload session in config/autoload.php file.
Remove that session_start().
Try to use flashdata. Flashdata is temporary session mostly used in your type of case where We need to redirect user to another page and display some success or error message.
Set flashdata:
$this->session->set_flashdata('item', 'value');
get flashdata:
$this->session->flashdata('item');
Here is the documentation link http://www.codeigniter.com/user_guide/libraries/sessions.html#flashdata
use autoload applications/config/autoload.php, to add session liblary and remove session_start();
$autoload['libraries'] = array('session');
Model pass post data vithout varibles, you can do like that:
controller:
public function verification()
{
$result = $this->site_model->login();
if ($result){
redirect ('site/index');
} else {
redirect ('site/login');
}
}
Model:
public function login()
{
$this->db->where('username' , $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$query = $this->db->get('users');
if ($query->num_rows()>0)
{
$res = $query->row_array();
$data = array(
'user_name' => $res['username'],
'logged_in' => TRUE,
'validated' => true
);
$this->session->set_userdata($data);
return true;
} else {
return false;
}
}
set the session variable in controller..this works for me nice
model
function Login($email,$pass){
$this->db->where('username' ,$email);
$this->db->where('password',$pass);
$query=$this->db->get('users');
if ($query->num_rows == 1) {
return true;
}
return FALSE;
}
Controller :
function varification(){
$this->load->model('login_model');
$email=$this->input->post('email');
$pass=$this->input->post('pass');
$success=$this->login_model->Login($email,$pass);
if ($success) {
$data = array(
'user_name' => $rows->username,
'logged_in' => TRUE,
'validated' => true
);
$this->session->set_userdata($data);
redirect ('site/index');
} else{ // incorrect id or password
redirect ('site/login');
}
}
now if you echo <?php echo $this->session->userdata('user_name');?> it will show the session username. you can echo it anywhere even in the view.hope this will help you
You don't need to use the core php session_start();
Make Sure you Have loaded session library in autoload.php
as:
$autoload['libraries'] = array("session");
or you can load session library manually : as
$this->load->library('session');
For Full Documentation You can refer : Read Documentation
please use this code to set session in codeigniter
$this->session->set_userdata('user_session', $user_session_data);
I was having the same problem and it got resolved using this code.Hope it works for you too!.
Setting session variables in Model, is not a good idea for any CMV framework (like codeigniter). Edit your Model's login() function so it returns a nice set of infos ...
function login ($username, $password)
{
$this->db->where('username' , $username);
$this->db->where('password', $password);
$query = $this->db->get('users');
if ($query->num_rows()>0)
{
foreach ($query->result() as $rows)
{
$data = array(
'user_name' => $rows->username,
'logged_in' => TRUE,
'validated' => true
);
}
return $data;
}
else
{
return false;
}
}
... and handle the session from the Controller.
public function verification()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$result = $this->site_model->login($username, $password);
if ($result == false)
{
redirect ('site/login');
//$this->load->view('login');
}
else
{
$this->session->set_userdata($result);
redirect ('site/index');
}
}
Also, in order to have session's data available to the view file, you need to pass them through your controller
$data['user_name'] = $this->session->userdata('user_name');
and then you can do whatever in your view file:
<?php if ($user_name != "") { ?>
Hello i think you need to change your model code
You are setting array in session and accessing direct user_name in session
I think below code will work for you,
function login ($username, $password)
{
$this->db->where('username' , $username);
$this->db->where('password', $password);
$query = $this->db->get('users')->row();
if (count($query) > 0)
{
$this->session->set_userdata('user_name', $query->username);
$this->session->set_userdata('logged_in', true);
$this->session->set_userdata('validated', true);
return true;
}
else
{
return false;
}
}
please follow below instructions.
make sure you have addedd session lib in autoload.php file so session will automatically loaded.
When you are using session in codigniter you don't have add session_start() at the start of the file because codigniter core system will handled this automatically.
It is good idea to set session variables in controller instead of model.
I hope this helps you in solving your problem.
thanks.
Here is my solution, hope will help.. :D
in your model.. i copy paste code bellow but i change a little..
function login ($username, $password)
{
$this->db->where('username' , $username);
$this->db->where('password', $password);
$query = $this->db->get('users');
if ($query->result())//if any record
{
$rows = $query->row();
$data = array(
'user_name' => $rows->username,
'logged_in' => TRUE,
'validated' => true
);
$this->session->set_userdata($data);
return true;
}
else
{
return false;
}
}
delete your session_start() in controller,, and then in your application/config/autoload.php
in this $autoload['libraries'] = array(); => add session like this
$autoload['libraries'] = array('session');
Thankyou.. :D
user default php session, like session_start() and $_SESSION, it is working for me. in php codeignatore