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.
Related
I use this code in my controller LOGIN and they are role type in my database: $users->isAdmin() $users->isOwner() $users->isMember()
public function dologin(Request $request){
$users = new Users;
$email = $request->input('u_email');
$password = $users->setPasswordAttribute($request->input('pwd1'));
//get user id from email
$user_id = $users->get_user_from_email($email);
foreach($user_id as $u){
$u_type = $u->u_type;
}
// Check validation
if (auth()->attempt(['u_email' => $email, 'password' => $password] )){
if($users->isAdmin() == $u_type){
return redirect('admin');
}
if($users->isOwner() == $u_type){
}
if($users->isMember() == $u_type){
}
}else{
}
}
Code in Users Model
public function isAdmin(){
return 0 ;
}
public function isOwner(){
return 1 ;
}
public function isMember(){
return 2;
}
My question:
-how to store role in session for logged in dashboard?
-how to declare in controller this role
Thanks you for all help
Note: the role type are integer 0, 1 and 2. I don't use enum type in my database for this role but integer
To use session in pages, make sure at the start of the page you have session_start(); (before any HTML tag).
After that, when he is logging in and everything is allright set $_SESSION["u_type"]=$u_type; and you can refer to it until you destroy your session.
To check in dashboard if he is admin, owner or member just check
//don't forget session_start(); at the begging of your file
if($_SESSION["u_type"]==0)
//admin
else if($_SESSION["u_type"]==1)
//owner
else if($_SESSION["u_type"]==2)
//member
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;
}
i am new to CodeIgniter and facing problem in adding user id(after user has logged in) from database to session data here is my code question may be asked before on SOF , after putting all my efforts i am asking this
//login-model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login_model extends CI_Model
{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
//get the username & password from tbl_usrs
public function get_user($usr, $pwd)
{
$sql = "select * from tbl_usrs where username = '" . $usr . "' and password = '" .$pwd . "' ";
$query = $this->db->query($sql);
return $query->num_rows();
}
/* public function set_session($username) {
$sql="SELECT * FROM tbl_usrs WHERE username='".$username."' LIMIT 1 ";
$result=$this->db->query($sql);
$row=$result->row();
$sess_data=array (
'id'=>$row->id,
'username'=>$username,
'is_login'=>TRUE
);
$this->session->set_userdata($sess_data);
} //set_seesion function ends
*/
}
?>
//login controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
print_r( debug_backtrace() );
//ini_set('memory_limit', '-1');
//ini_set('max_execution_time', 3000);
ini_set('display_errors',1);
error_reporting(E_ALL);
class LoginController extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper('form');
$this->load->helper('url');
$this->load->helper('html');
$this->load->database();
$this->load->library('form_validation');
}
public function index()
{
//load the login model
$this->load->model('login_model');
// $qry=$this->login_model->validate();
//get the posted values
$username = $this->input->post("username");
$password = $this->input->post("password");
$user_id = $this->input->get("user_id");
//set validations
$this->form_validation->set_rules("username", "username", "trim|required");
$this->form_validation->set_rules("password", "password", "trim|required");
if ($this->form_validation->run() == FALSE)
{
//validation fails
redirect('Homecontroller/index'); //make new controller for loading a form again
echo "Validation fails"; // even for no name and passwrd
}
else
{
//validation succeeds
if ($this->input->post('submit') == "Login")
{
//check if username and password is correct
$usr_result = $this->login_model->get_user($username, $password);
if ($usr_result > 0) //active user record is present
{
//set the session variables
$sessiondata = array(
'user_id' => $user_id,
'username' => $username,
'password'=>$password,
'is_login' => TRUE
);
//$this->login_model->set_session($username);
$this->session->set_userdata($sessiondata);
print_r($this->session->all_userdata()); //to check
redirect(base_url("Site/member_area"));
return $username;
}
else
{
$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Invalid username and password!</div>');
redirect('Homecontroller/index');
}
}
else
{
redirect('login/home3');
}
}
}
}?>
when i am try to print session data in view i am getting user_id=> empty
None of these variables will be available to you for assignment:
'user_id' => $user_id,
'username' => $username,
'password'=>$password,
The reason for this is that you've used:
$usr_result = $this->login_model->get_user($username, $password);
However, that is only going to be the result of the number of rows returned:
public function get_user($usr, $pwd)
...
return $query->num_rows();
So now, $usr_result will be the number of rows returned, not the data of the user in question.
So, what you should do, is instead set the session data in that login function above return $query->num_rows(); and below $query=.
public function get_user($usr, $pwd){
....
$query = $this->db->query($sql);
$this->session->set_userdata('sessiondata', $query->row_array());
}
Note that as we only retrieve 1 user from our query ever, we also would only ever want to get 1 row back. Furthermore, you're wanting to store an associative array, and not an object, so we use $query->row_array() to get back 1 row formatted as an array where the key is the column name and the value is the columns result.
Now, do a echo '<pre>', print_r($this->session->userdata('sessiondata'), true),'</pre>'; to get a formatted list of that object which contains the array. Then you can map names accordingly.
Sidenote, i would not store the password in an session.
I'm new to codeigniter and php, few days only, so I need a little help.
I'm trying to put some data in my cookie from table so I can check where to redirect user after login. In table users there are two columns named Admin and Company with one or zero if user is or not, and then i wish to insert that information to cookie.
function conformation in user_controler is:
function conformation(){
$this->load->model('user');
$q = $this->user->confr();
if($q){
$data = array(
'username' => $this->input->post('username'),
'Admin' => $this->input->post($a = $this->user->getAdmin), // get 1/0 from users column Admin
'Company' => $this->input->post($c = $this->user->getComp),
'login' => true
);
if( $a == 1 ){ //is admin redirect to admin view
$this->session->set_userdata($data);
redirect('user_controler/useradm');
}
if($c == 1){ //if company redirect to company view
$this->session->set_userdata($data);
redirect('user_controler/usercomp');
}
$this->session->set_userdata($data);// if common user redirect to user view
redirect('user_controler/userpro');
}
else{ // if nothing above redirect to login page
redirect('user_controler/log');
}
}
And in user model:
function getAdmin{
$this->db->where('Admin', 1);
$a = $this->db->get('users');
}
function getComp{
$this->db->where('Company', 1);
$a = $this->db->get('users');
}
function conf(){
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$q = $this->db->get('users');
if($q->num_rows == 1 ){
return TRUE;
}
}
Also have site controller for checking login
class Site extends CI_Controller{
function __construct() {
parent::__construct();
$this->login();
}
function login(){
$login = $this->session->userdata('login');
if(!isset($login) || login != TRUE){
$this->log;
die();
}
}
}
Of course it's not working because i should probably check these column some other way but I don't know how. I Also have enabled table ci_session and it's work perfectly without Admin and Company.
Hello and welcome to Stackoverflow.
Here are my updates to the code (I have annotated my changes):
function conformation(){
$this->load->model('user');
if($this->user->confr()){ //$q wasn't needed, as you are only using this twice
$user = $this->input->post('username'); //I have added this as I will be referring to it a couple of times.
$data = array(
'username' => $user,
'Admin' => $this->user->getAdmin($user), // Your method was questioning the original form looking for data that it would never find - This will question your model.
'Company' => $this->user->getComp($user), //Same as above
'login' => true
);
$this->session->set_userdata($data); //It doesn't matter who the user is, we shall set the data to start with.
if($this->user->getAdmin($user)){ //is admin redirect to admin view
redirect('user_controler/useradm');
}
elseif($this->user->getComp($user)){ //if company redirect to company view
redirect('user_controler/usercomp');
}
else { //Redirect non-privileged users.
redirect('user_controler/userpro');
}
}
else{ // if nothing above redirect to login page
redirect('user_controler/log');
}
}
Users Model:
function getAdmin($user){
$this->db->where('username', $user); //Before you was just returning everyone who is an admin This instead finds the user
$a = $this->db->get('users');
foreach($a as $u) {
if($u["Admin"]==1) { return true; } //This finds if the user is a admin or not, and the function will now return a value (true)
}
}
function getComp($user) {
$this->db->where('username', $user);
$a = $this->db->get('users');
foreach($a as $u) {
if($u["Company"]==1) { return true; }
}
} //Edited similar to the function above
function conf(){
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$q = $this->db->get('users');
if($q->num_rows == 1 ){
return TRUE;
}
}
Lastly your login function:
function login(){
$login = $this->session->userdata('login');
if(!isset($login) || $login != TRUE){ //You weren't referring to your $login variable
$this->log;
die();
}
}
Hopefully this helps with your problems, let me know if you need any amendments.
I am at the tail end of signing in a created user to an account. I've commented out my flow and everything seems to make since, however I am missing a step or two because now the post data password is not being hashed.
CONTROLLER:
function validate_credentials()
{
// WHEN THE VIEW IS LOADED THIS FUNCTION IS CALLED AND LOADS MODEL AS WELL AS DEFINES THE SALT VARIABLE AND LOADS THE ENCRYPTING HELPER LIBRARY
$this->load->model('user_model', 'um');
$login = $this->input->post('submit');
$salt = $this->_salt();
$this->load->library('encrypt');
//IF THE SUBMIT BUTTON IS TRIGGERED THE POST DATA IS SENT TO THE VALIDATE FUNCTION IN THE MODEL VIA VARIABLES CREATED
if($login)
{
$data = array(
'email' => $this->input->post('email'),
'password' => $this->encrypt->sha1($user->salt. $this->encrypt->sha1($this->input->post('password')))
);
$user = $this->um->validate($data);
}
// IF ITS A REAL USER OPEN THE GATE AND LET THEM IN
if($user)
{
$this->session->set_userdata($data);
redirect('account/dashboard');
}
else
{
$this->index();
}
}
MODEL:
function validate($data)
{
$this->output->enable_profiler(TRUE);
// TAKING THE DATA FROM THE MODEL AND CHECKING IT AGAINST THE STORED INFO IN THE DB
$query = $this->db->where($data)->get('users', 1);
if($query->row())
{
return $query->row();
}
}
thanks in advance
$user->salt should just be $salt.