Model
function Updateno($user,$data){
$this->db->where('username', $user);
$this->db->update('user', $data);
}
Controller
//user login function
function Ulogin(){
if($this->session->userdata('user'))
{
$data['user'] = $this->session->userdata('user');
$this->load->view("User/choosecategory",$data);
}
else
{
$data = array(
'username' =>$this->input->post('username'),
'password' =>$this->input->post('password'),
);
$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('User/login');
}
else
{
if($this->user_model->userlogin($data)==false)
{
$data['error'] = '<div class="alert alert-danger text-danger">Please Provide Valid Username/Password!</div>';
$this->load->view('User/login',$data);
}
else
{
$this->session->set_userdata('user',$data['username']);
$data['user'] = $this->session->userdata('user');
$counter = array(
'logged_in' =>'logged_in'+1
);
$this->user_model->Updateno($this->session->userdata('user'),$counter);
$this->load->view("User/choosecategory",$data);
}
}
}
}
I want whenever user login successfully my logged_in cloumn value increase by 1 but in this code the value of logged_in column always to 1,plz help me anyone here
the only thing you need to do here is to increment the value by 1
try the following piece of code
your model
function Updateno($user)
{
$this->db->where('username', $user);
$this->db->set("logged_in","logged_in+1",false);
$this->db->update('user');
}
and in your controller
$this->user_model->Updateno($this->session->userdata('user'));
What you want to do is this:
$value = explode("logged_in", $counter['logged_in']); //get the number of the counter
$counter['logged_in'] = 'logged_in' . ((int)$value[1] +1); //increase value by 1
This will get the current counter value from your string and increase it by 1
I made a demo to show how you can use it
DEMO: https://eval.in/773121
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;
}
}
Using codeigniter hashed my password with BCRYPT, seems that everytime I login I redirect to the success page. So I am figuring password verify is not working, even if I enter the incorrect login it still redirects, does not throw the form_validation errors either.
I used the documentation to set it up along with the guides on SO. Will eventually go to Ion Auth but want to know how to fix this. As I am still learning code igniter mvc.
Model
class user_model extends CI_Model{
public function register($encrypt_pass){
$data = array(
'name'=> $this->input->post('name'),
'email'=> $this->input->post('email'),
'username'=> $this->input->post('username'),
'password'=>password_hash($encrypt_pass,PASSWORD_BCRYPT)
);
return $this->db->insert('customers',$data);
}
public function login($username,$password){
//validate the inputs from form
$this->db->where('username',$username);
$query = $this->db->get('customers'); //customers is the table
$result = $query->row_array();
if(!empty($result) && password_verify($password, $result['password'])){
return $result;
}
else{
return "false";
}
}
}
Controller
public function 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 {
//Getting username
$username = $this->input->post('Username');
//Getting and ecrypting password
$password = $this->input->post('Password');//password hashed
$user_id = $this->user_model->login($result);
//checking for user/pass correct will set session if so
if($user_id){
$this->session->set_flashdata('user_loggedin','You are now logged in');
redirect('posts');
}
// If combo is incorrect will redirect
else{
$this->session->set_flashdata('user_loggedin','Login Failed, Please Try
Again');
redirect('users/login');
}
}
}
}
Here is a simple working login code, there are many ways how to do it, it's just an example.
ON YOUR MODEL
Create a function that will check/get the username's password.
public function _getUserPassword($user_name){
$data = array();
$this->db->select('PASSWORD');
$this->db->from('tbl_user');
$this->db->where('USER_NAME', $user_name);
$query = $this->db->get();
if($query->num_rows() > 0){
foreach($query->result_array() as $field_name => $field_value){
$data = $field_value;
}
return $data;
}
else{
return false;
}
}
I've seen your's just selecting it.
We need to use that _getUserPassword function on we call it verify function
function verify($username, $password){
$data = array();
$userNameExists = $this->_getUserPassword($username);
if(password_verify($password, $userNameExists['PASSWORD'])){
$this->db->select('*');
$this->db->from('tbl_user AS user');
$this->db->where('USER_NAME', $username);
$query = $this->db->get();
if($query->num_rows() > 0){
foreach($query->result_array() as $field_name => $field_value){
$data = $field_value;
}
return $data;
}
else{
return false;
}
}
else{
return false;
}
}
So if the verification is success it will return the data to your controller, Let's use your controller.
Let's assume that you changed the models
ON YOUR CONTROLLER
public function 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 {
//Getting username
$username = $this->input->post('Username');
//Getting and ecrypting password
$password = $this->input->post('Password');
$user_id = $this->user_model->verify($username,$password);
//checking for user/pass correct will set session if so
if($user_id){
$this->session->set_userdata('user_loggedin','You are now logged in');
redirect('posts');
}else{
//DO NOT SET USER DATA SESSION HERE UNLESS IT WILL AUTOMATICALLY LOGGED IN.
redirect('users/login');
}
}
}
Hope this helps!
where you are checking that password is matching or not.
try this in your controller.after user check.
if($user>0){
if (password_verify($this->input->post('Password'), $user_id['password'])) {
//success message
}
else{
//error message.password is invalid
}
I need to capture login user and when i add question i need to save the corresponding user id in the questions table.i'm getting user id when i login but it is not saving in the question table
Controller with store function
public function store(Request $request)
{
//
$last_que = Question::orderBy('question_id', 'desc')->first();
if ($last_que != null) {
$old_queId = $last_que->question_id;
$old_queId = $old_queId + 1;
} else {
$old_queId = 1;
}
$qorder=$request->input('order');
$question=new Question();
$quest=$question->checkDuo($qorder);
if(count($quest)==0)
{
$que=Question::create([
'question'=>$request->input('question'),
'question_id'=>$old_queId,
'question_type'=>$request->input('qtype'),
'question_schedul'=>$request->input('qschedule'),
'created_user_id'=>Session::get('created_id'),
'order_no'=>$request->input('order')
]);
if($que)
{
return redirect()->route('questions.index')->with('success', 'Successfully saved');
}
}
else
{
return redirect()->back()->with('fail', 'Unable to save..! Entry with same order no. already exist');
}
}
in Login index file this is i used capture the user id
<?php
if (!empty($id)) {
Session::put('created_id', $id);
}
?>
Login controller
public function postSignIn(Request $request)
{
if (Auth::attempt(['username' => $request['username'], 'password' => $request['password']])) {
$user = DB::table('users')->where([['username', '=', $request['username']], ['status', '=', '0']])->first();
$user_id = $user->user_id;
return redirect()->route('dashboard', $user_id)->with('message', 'State saved correctly!!!');
} else {
return redirect()->back();
}
}
Get user ID. use something like this.
Auth:user()->id;
Or you can use
Session::getId();
Change this line,
'created_user_id'=>Session::get('created_id'),
To,
'created_user_id'=>Auth::id(),
You used $user_id
return redirect()->route('dashboard', $user_id)->with('message', 'State saved correctly!!!');
Than asking:
if (!empty($id)) {
This $id will be always empty so use:
<?php
if (!empty($user_id)) {
Session::put('created_id', $user_id);
}
?>
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'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.