I want to create a profile view for the user that is currently logged in. I created a session_data array for when you log in that only contains their username. How would I retrieve the other values from the row depending on who is logged in? Do I have to add all that information to the session_data array?
I have the values first_name, last_name, & date_joined that I want to display alongside username.
Login Controller:
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('templates/header');
$this->load->view('login');
$this->load->view('templates/footer');
}
function login_validation()
{
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run())
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$this->load->model('login_model');
if ($this->login_model->can_login($username, $password))
{
$session_data = array(
'username' => $username
);
$this->session->set_userdata($session_data);
redirect('home');
}
else {
$this->session->set_flashdata('error', 'Invalid Username and Password');
redirect('login');
}
}
else {
$this->index();
}
}
function enter()
{
if ($this->session->userdata('username') != '') {
echo "Welcome " . $this->session->userdata('username');
echo 'Logout';
}
else {
redirect('login');
}
}
function logout()
{
$this->session->unset_userdata('username');
redirect('login');
}
}
User View:
<h4><?php echo $_SESSION['username']; ?></h4>
You'll need a method in login_model that retrieves the username info based on the username you send to it.
Something like this:
function get_user($username)
{
$this->db->select(*);
$this->db->from('users');
$this->db->where('username', $username);
$query = $this->db->get();
if ($this->db->affected_rows())
{
return $query->row();
}
}
On the other hand, I recommend you to use an existing authentication library.
Ion Auth is pretty good.
Good luck!
Related
I have a login for with username and password , after the user logged in , the user redirect to dashboard , and if the user press the back button of browser it will redirect the user to login page , while i want to redirect the user to dashboard as is already logged-in.i would appreciate if anyone can help me to implement that.
Here is my login. php controller
<?php
class Login extends CI_controller {
public function __construct()
{
parent::__construct();
$this->load->library('form_validation');
$this->load->library('encrypt');
$this->load->model('login_model');
}
function index()
{
//echo CI_VERSION; die;
//echo $this->encrypt->encode('123456');
//echo "<br>".$this->encrypt->decode('ADxTYFI1ATFSYwFn');
//die;
$this->load->view('login');
}
function validation()
{
// print_r($_REQUEST);
// die;
$this->form_validation->set_rules('username', 'Username', 'required|trim' );
$this->form_validation->set_rules('password' , 'Password' , 'required');
if ($this->form_validation->run())
{
$res = $this->login_model->can_login($this->input->post('username'), $this->input->post('password'));
if(is_array($res)){
$stored_password = $res['stored_password'];
$row = $res['row'];
if(password_verify($this->input->post('password'),$stored_password)){
$userID = $row->id;//die;
$this->session->set_userdata('admin',$userID);
redirect('admin/dashboard');
}else{
$this->session->set_flashdata ('message','Invalid Credentils');
redirect('admin/login');
}
}else{
$this->session->set_flashdata ('message','Invalid Credentils');
redirect('admin/login');
}
}
else
{
$this->index();
}
}
}
And here is my login_model.php
<?php
class Login_model extends CI_Model
{
function can_login($username, $password)
{
$this->db->where('username', $username);
$query = $this->db->get('user_login');
if($query->num_rows() > 0)
{
$result = $query->row();
//print_r($result);die;
$stored_password = $result->password;
$return = array('stored_password'=> $stored_password , 'row' => $result);
return $return;
}
else
{
return FALSE;
}
}
And here is my dashboard.php controller
<?php
class Dashboard extends CI_Controller
{
function __construct()
{
parent::__construct();
if(!$this->session->userdata('admin'))
redirect('admin');
// else{
// redirect('admin/dashboard');
// }
}
function index()
{
$this->load->view('admin/dashboard');
}
function logout()
{
$this->session->sess_destroy();
redirect('admin');
}
}
Solved,
I solved the problem by adding session in my login.php controller
public function __construct()
{
parent::__construct();
if($this->session->userdata('admin'))
redirect('dashboard');
$this->load->library('form_validation');
$this->load->library('encrypt');
$this->load->model('login_model');
}
I have very simple page that requires login to view. I have a login controller and view that will redirect to the main page after successful login. However, i want to detect whether user is logged in if the user directly access the main page link, if not logged in, then the user should be redirect back to the login page.
My Login controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function index()
{
$this->load->view('login_view');
}
public function process()
{
$user = $this->input->post('user');
$pass = $this->input->post('pass');
if ($user=='admin' && $pass=='123')
{
$this->session->set_userdata(array('user'=>$user));
redirect("Report");
}
else{
$data['error'] = 'Your Account is Invalid';
$this->load->view('login_view', $data);
}
}
public function logout()
{
$this->session->unset_userdata('user');
redirect("Login");
}
}
?>
and my Login view:
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<?php echo isset($error) ? $error : ''; ?>
<form method="post" action="<?php echo base_url('Login/process'); ?>">
<table cellpadding="2" cellspacing="2">
<tr>
<td><th>Username:</th></td>
<td><input type="text" name="user"></td>
</tr>
<tr>
<td><th>Password:</th></td>
<td><input type="password" name="pass"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</form>
</body>
</html>
while the login process is working good, but i'm not sure how to get the session from my main page to detect whether user is logged in. I know i should add some validation in the main controller but i'm not sure how, please help thank you.
main controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class EstoreReport extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('ReportModel');
}
public function index()
{
$report=new ReportModel;
$data['data']=$report->get_report();
$this->load->view('includes/header');
$this->load->view('Report/list',$data);
$this->load->view('includes/footer');
}
You can create a function and call it to check whether the user is logged in or not
public function is_logged_in()
{
$user = $this->session->userdata('user_data');
return isset($user);
}
Assuming you have session helper autoloaded, just like validation on the Login controller, you could set the validation in the index method of the Main / Report controller :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class EstoreReport extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('ReportModel');
}
public function index()
{
if (!isset($this->session->userdata('user'))) {
redirect("Login");
} else {
$report=new ReportModel;
$data['data']=$report->get_report();
$this->load->view('includes/header');
$this->load->view('Report/list',$data);
$this->load->view('includes/footer');
}
}
You could use $this->session->has_userdata() as per CI docs
So
// Write a boolean returning method
/**
* Returns if there is a user session
*
* #return bool
*/
public function isLoggedIn()
{
return $this->session->has_userdata($some_defined_key_like_user_id);
}
...
// Then in your index controller method
/**
* Index controller method
*
* #return void
*/
public function index()
{
$this->isLoggedIn() ? $this->load()->view('login') : redirect("Report");
}
Just simple configure in your controller index():
Use $this->session->userdata('user') == NULL to check whether user is logged in
public function index()
{
if($this->session->userdata('user') == NULL)
{
redirect('Login');
}
else
{
$report=new ReportModel;
$data['data']=$orders->get_report();
$this->load->view('includes/header');
$this->load->view('Report/list',$data);
$this->load->view('includes/footer');
}
}
Try this
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('loginmodel', 'login');
$this->load->library('form_validation');
}
public function index() {
$this->load->view('admin/login');
}
// Check for user login process
public function user_aouth() {
$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->session->set_flashdata('error', 'Invalid Username and Password');
redirect('login');
} else {
$username = $this->input->post('username');
$password = $this->input->post('password');
$data = array(
'username' => $username,
'password' => $password
);
if ($this->login->check_valid_user_details($data)) {
$session_data = array(
'username' => $username
);
$this->session->set_userdata($session_data);
//redirect to admin user dashboard
redirect('dashboard');
} else {
$this->session->set_flashdata('error', 'Invalid Username and Password');
redirect('login');
}
}
}
public function logout() {
$this->session->unset_userdata('username');
$this->session->sess_destroy();
redirect('login');
}
}
In your login model
public function check_valid_user_details($data) {
$condition = "username=" . "'" . $data['username'] . "'" . "AND password=" . "'" . $data['password'] . "'";
$c = $this->db->select('*')
->from('admin')
->where($condition)
->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return FALSE;
}
}
Use this at the top of every page under dashboard
if($this->session->userdata('username') == NULL){
redirect('login');
}
controller
public function index()
{
//redirect to dashboard
$this->dashboard();
}
public function dashboard()
{ //session wise operating isset session-> dashboard ,else login page
if ($this->session->userdata('userName')) {
//if user found
return $this->load->view('dashboard');
} else {
//if "no user found"
return $this->load->view('login');
}
}
public function login_check()
{ //functions retrives two values 1-user type 2-userId
$data['userdata'] = $this->Mdl_login->Login_check();
if ($data['userdata'] == false) {
$this->load->view('login', $data);
} else {
redirect(base_url('index.php/dashboard'), 'refresh');
}
}
function logout()
{ //session destroy function
$this->session->unset_userdata('userName');
redirect(base_url(), 'refresh');
}
Model
function Login_check()
{
$username = $this->input->post('UserName');
$password = $this->input->post("PassWord");
//check with your value
$this->db->where('userName', $username);
$this->db->where('password', $password);
$qry_getuserdata = $this->db->get('user_tbl');
if ($qry_getuserdata->num_rows() > 0) {
$result = $qry_getuserdata->result();
$userid = $result[0]->userId;
$usertype = $result[0]->userType;
$email = $result[0]->email;
$this->session->set_userdata('userName', $username);
$this->session->set_userdata('userId', $userid);
$this->session->set_userdata('userType', $usertype);
$this->session->set_userdata('email', $email);
return true;
} else {
return false;
}
}
Now you can access your session data anywhere
if(isset($_SESSION['userName'])){ $data['userName']= $_SESSION['userName']; }
You can have true or false from below function call, Call this function in your controller and then redirect as per the response.
$this->session->userdata( 'logged_in' );
I have created library in codeigniter library and it's named account. I want to get all session data when I call this library, how can I do that. I tried this:
if ($this->account->isLoggedIn()){
$this->ci->session->userdata('isLoggedIn');
}
First Include the Library:
$this->load->library('session');
Store the data in array which you want to store in session :
$data= array(
'username' => 'username',
'password' => 'password',
'email'=>'emailid'
'logged_in' => 'login id'
);
Store this data in session:
$this->session->set_userdata($data);
You can use this data any time for example if you want loginid from session you can write:
$loginid= $this->session->userdata('logged_in');
When Logout:
$this->session->unset_userdata(array("username"=>"","logged_in"=>"","password"=>"","email"=>""));
$this->session->sess_destroy();
redirect('loginpage');
If you don't want to direct access the pages create one model and add this code in it and auto load that model.
public function valid_allowed()//check user is login or not
{
$session = $this->session->userdata('username'); //here you can take loginid, email whatever you store in session
if(!$session)
{
redirect('login');
}
}
To auto load that model
Go to application->config->autoload.php: this line:
$autoload['model'] = array('model name');
Change your model:
class LoginModel extends CI_model
{
public function login($name, $pass)
{
$this->db->select('name,pass');
$this->db->from('members');
$this->db->where('name',$name);
$this->db->where('pass',$pass);
$query = $this->db->get();
if($query->num_rows() == 1)
{
$row=$query->row();
$data=array(
'username'=>$row->u_username,
'id'=>$row->id,
'email'=>$row->email
'password'=>$row->u_password);
$this->session->set_userdata($data);
return true;
}
else
{
return false;
}
}
}
Change your verifyUser function:
public function verifyUser()
{
$name = $this->input->post('username');
$pass = $this->input->post('password');
$this->load->model('LoginModel');
$result=$this->LoginModel->login($name, $pass))
if(!$result)
{
$this->form_validation->set_message('verifyUser','Incorrect Email or Pass');
return false;
redirect('LoginController/checklogin');
}
else
{
redirect('dashboard'); //user is valid so goto dashboard
}
}
I want to connect from one controller in one module to another controller in another module. I want to go from my login module to my dashboard module and use a function inside the dashboard module. Just basically switch from my login module to my dashboard module. Here is my login controllers and my dashboard controller.
class Login extends MX_Controller {
function index()
{
$this->load->view('includes/header');
$this->load->view('login_form');
$this->load->view('includes/footer');
}
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('login/site/members_area');
}
else // incorrect username or password
{
$this->index();
}
}
function signup()
{
//$data['main_content'] = 'signup_form';
//$this->load->view('includes/template', $data);
$this->load->view('includes/header');
$this->load->view('signup_form');
$this->load->view('includes/footer');
}
function create_member()
{
$this->load->library('form_validation');
// field name, error message, validation rules
$this->form_validation->set_rules('first_name', 'Name', 'trim|required');
$this->form_validation->set_rules('last_name', 'Last Name', 'trim|required');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|callback_check_if_email_exists');
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]|max_length[15]|callback_check_if_username_exists');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
$this->form_validation->set_rules('password2', 'Password Confirmation', 'trim|required|matches[password]');
if($this->form_validation->run() == FALSE) // didn't validate
{
$this->load->view('includes/header');
$this->load->view('signup_form');
$this->load->view('includes/footer');
}
else
{
$this->load->model('membership_model');
if($query = $this->membership_model->create_member())
{
$data['account created'] = 'Your account has been created. <br /> <br /> You may now login';
$this->load->view('includes/header');
$this->load->view('signup_successful', $data);
$this->load->view('includes/footer');
}
else
{
$this->load->view('includes/header');
$this->load->view('signup_form');
$this->load->view('includes/footer');
}
}
}
function check_if_username_exists($requested_username)
{
$this->load->model('membership_model');
$username_available = $this->membership_model->check_if_username_exists($requested_username);
if ($username_available)
{
return TRUE;
}else{
return FALSE;
}
}
function check_if_email_exists($requested_email)
{
$this->load->model('membership_model');
$email_available= $this->membership_model->check_if_email_exists($requested_email);
if ($email_available)
{
return TRUE;
}else{
return FALSE;
}
}
function logout()
{
$this->session->sess_destroy();
$this->index();
}
}
my second login controller
class Site extends MX_Controller {
public function __construct()
{
parent::__construct();
$this->is_logged_in();
$this->lang->load('login/login/', 'english');
}
function members_area()
{
$this->load->view('logged_in_area');
//$this->load->module('dashboard/dashboard');
//$this->load->view('home');
}
function is_logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if(!isset($is_logged_in) || $is_logged_in != true)
{
echo 'You don\'t have permission to access this page. Login';
die();
//$this->load->view('login_form');
}
}
}
the controller in my dashboard module has a function called home I am trying to connect to and use. And the home function of the dashboard has a connection to another module but I cannot get the connection from login to dashboard to work. Also the way my login works I need to connect to the dashboard module through my members_area function. All help greatly appreciated.
Assuming you're using this library
From controller you can use Modules::load or $this->load-module
$moduleInstance = $this->load->module('yourmodule');
// or
$moduleInstance = Modules::load('yourmodule');
// Now you can call any public module controller method
$moduleInstance->somePublicMethod($arg1, $argn);
// you can also use $this->yourmodule as a model instance
Hope this helps
I have codeigniter installed on my localhost
The main.php controller is
class Main extends CI_Controller {
public function index()
{
$this -> login();
}
public function login()
{
$this->load->view('login');
}
public function login_validation() {
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('password','Password','required|md5');
if($this->form_validation->run())
{
redirect('main/members');
}
else
{
$this->load->view('login');
}
}
}
The login is working page is coming,but after I fill the username and password,should take me to login/main/login_validation and from there the function login_validation() should either redirect to main/members or show me the login page.But what happens is when I submit the form,the object not found error is coming.Can anyone help me out?
form is
form_open('main/login_validation');
To answer what I think your question is getting at, you're using the form_validation class wrong. You should be testing whether or not the form_validation->run() is TRUE (all fields passed validation) or FALSE (there was an error in one or more of the inputs). Structure you code like such:
public function login_validation() {
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('password','Password','required|md5');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('login');
}
else
{
redirect('main/members');
}
}
This is covered in the CodeIgniter documentation here.
in your controller ..you could try this..
function index()
{
//This method will have the credentials validation
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run() == FALSE)
{
//Field validation failed. User redirected to login page
$this->load->view('login');
}
else
{
$this->check_database();
//redirect('home');
}
}
function check_database()
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
$password = $this->input->post('password');
//query the database
$query_result = $this->model_login->login($username, $password);
if($query_result)
{
$this->load->view('main/members');
}
else
{
redirect('login');
}
}
in model
function login($username,$password){
$query = $this->db->query("SELECT * FROM `login` WHERE `username`= '".$username."' AND
password='".$password."' LIMIT 1");
if ($query->num_rows() > 0)
return TRUE;
else
return FALSE;
}