Only show user_id and username after log in in codeigniter - codeigniter

I have a login and registration system in codeignitor.
This is my controller -
function index()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
//$data['username'] = $session_data['username'];
$data = array(
'user_id'=>$session_data['user_id'],
'username'=>$session_data['username'],
'firstname'=>$session_data['firstname'],
'lastname'=>$session_data['lastname']
);
$this->load->view('home_view', $data);
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
this code only show me the user_id and username. but not showing the firstname and lastname. Please help me ...

Considering that you have set your session like this,
$data = array(
'user_id'=>id,
'username'=>"name",
'logged_in'=>1,
);
$this->session->set_userdata($data);
To access values from session,
$this->session->userdata("name of session variable");
In your case,
$this->session->userdata("user_id");// for user id
$this->session->userdata("user_name");// for user name

if($result) {
$sess_array = array();
foreach($result as $row) {
$sess_array = array(
'user_id' => $row->user_id,
'username' => $row->username
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
} else {
$this->form_validation->set_message('check_database', 'Invalid username or password');
return false;
}
In your above given code I can't find the firstname in session setting. But you are trying to get firstname then how will the code provide you the firstname.

Related

How can I store the web push notification settings after the login in database

I want to send web push notification on the browser. I used this tutorial to
send the notification. This is working fine and show the details.
{
"endpoint":"https://fcm.googleapis.com/fcm/send/ftB1OYn5bJY:APA91bGNcquGDcUXr29JiVV5Zos4Vi7FzmZ_wJQMITEXt8FlVBRBtgrPdLnPR6GALtnCOe9RNPP1cmC_bkv9D1BE1o6_-0cMXQsodpPoRCeOP5EDt6EwqK0ys36MbCi3HNTWf7ZcItVi",
"expirationTime":null,
"keys":{"p256dh":"BLJQqNovnlJ28d5xteX8whwdby6l0BYLvC_iyNtY2nO7YXQSI-EOvdOs1LXy8F_EuH2MZi0FU_HoCO-5GRQYYVQ",
"auth":"tDcEgiy5M5tJ3_vXuuQ9uw"}
}
but I want to integrate with my Laravel API.
After the user login, I want to save the endpoint, public key, and auth
to the database.
Login Controller
public function authenticate(Request $request)
{
$credentials = $request->only('username', 'password');
// return $credentials;
$response = array(
'status' => 'Failed',
'msg' => '',
'is_success' => false,
'data' => ''
);
try {
if (!$token = JWTAuth::attempt($credentials)) {
$response["msg"] = "Wrong Username or Password";
$response["status"] = "Failed";
$response["is_success"] = false;
} else {
if (Auth::user()->is_active == 0) {
$response["msg"] = "Your account has not been activated";
$response["status"] = "Failed";
$response["is_success"] = false;
} else {
$data = array();
$user = User::find(Auth::user()->id);
$data['id'] = $user->id;
$data['fname'] = $user->fname;
$data['lname'] = $user->lname;
$data['email'] = $user->email;
$data['username'] = $user->username;
$response["msg"] = "Login Successfully";
$response["status"] = "Success";
$response["data"] = compact('token');
$response["user"] = Auth::user();
}
}
} catch (\Exception $th) {
$response["msg"] = $th->getMessage();;
$response["status"] = "Failed";
$response["is_success"] = false;
}
return $response;
}
I think the best way to solve this, is to make another model for that data, a one to one relationship between user model and push notification data model. Make a controller for CRUD operations on this new model, and just have another http call from the front end to store the data.

Change password for logged in user (codeigniter)

Is there any solution how to make change password for logged in user? i want to make a change password for logged in user, the code i made only change user password with user id number 1. it doesn't change for logged in user. so any idea?
this is my controller:
public function update(){
$this->form_validation->set_rules('password', 'Current Password', 'required|alpha_numeric|min_length[6]|max_length[20]');
$this->form_validation->set_rules('newpass', 'New Password', 'required|alpha_numeric|min_length[6]|max_length[20]');
$this->form_validation->set_rules('confpassword', 'Confirm Password', 'required|alpha_numeric|min_length[6]|max_length[20]');
if($this->form_validation->run()){
$cur_password = $this->input->post('password');
$new_password = $this->input->post('newpass');
$conf_password = $this->input->post('confpassword');
$this->load->model('queries');
$userid = '1';
$passwd = $this->queries->getCurrPassword($userid);
if($passwd->password == $cur_password){
if($new_password == $conf_password){
if($this->queries->updatePassword($new_password, $userid)){
echo 'Password updated successfully';
}
else{
echo 'Failed to update password';
}
}
else{
echo 'New password & Confirm password is not matching';
}
}
else{
echo'Sorry! Current password is not matching';
}
}
else{
echo validation_errors();
}
This is my model:
public function getCurrPassword($userid){
$query = $this->db->where(['id'=>$userid])
->get('users');
if($query->num_rows() > 0){
return $query->row();
} }
public function updatePassword($new_password, $userid){
$data = array(
'password'=> $new_password
);
return $this->db->where('id', $userid)
->update('users', $data); }
You can initialize a session when the user logs in to the system at the beginning, and store the information of the user in that session, like this:
function login() {
$query = $this->db->select(*)
->from('table_name')
->where('your parameters....');
return $query->row();
}
function index() {
$userid = $this->login()->id; //id of the user which is currently logged IN
$this->session->set_userdata('current_userId', $userid);
}
You have now stored the id of currently logged IN user in the session. You can access the id by $this->session->userdata('current_userId');. Replace your $userid = '1' by the session data. Also, you will have to load the session library in order to do so.

Codeigniter User's Data

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;
}

resetting password in codeigniter

i'm new to codeigniter, and i am attempting to create a password reset system
this is my controller:
public function changePassword(){
if($this->session->userdata('loginuser'))
{
$session_data = $this->session->userdata('loginuser');
$email = $this->session->userdata('email');
$data['email'] = $email;
$data['title'] = 'Change my Password | Watch Stop';
$this->load->view('template/header', $data);
$this->load->view('watch_stop/vpassword', $data);
$this->load->view('template/footer');
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
public function reset_password(){
if($this->session->userdata('loginuser'))
{
$session_data = $this->session->userdata('loginuser');
$email = $this->session->userdata('email');
$data['email'] = $email;
//validating form
$this->form_validation->set_rules('old_password','Old Password','trim|required|min_length[5]|md5');
$this->form_validation->set_rules('new_password','New Password','trim|required|min_length[5]|matches[cnew_password]|md5');
$this->form_validation->set_rules('cnew_password','Confirm Password','trim|required||md5');
if ($this->form_validation->run() == FALSE)
{
$this->changePassword();
//$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Failed to update password</div>');
}else {
$query=$this->customer_model->change_password();
$data = array( "main_content" => 'includes/memberadmin/memberadmin_cpass_process',
"query" => $query
);
$this->load->view('includes/memberadmin/template',$data);
}
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
this is my model:
function change_password(){
$this->db->select('id');
$this->db->where('email',$this->session->userdata('email'));
$this->db->where('password',$this->input->post('old_password'));
$query=$this->db->get('user');
if ($query->num_rows() > 0)
{
$row = $query->row();
if($row->email===$this->session->userdata('email'))
{
$data = array(
'new_password' => $this->input->post('new_password')
);
$this->db->where('email',$this->session->userdata('email'));
$this->db->where('new_password',$this->input->post('old_password'));
if($this->db->update('user', $data))
{
return "Password Changed Successfully";
}else{
return "Something Went Wrong, Password Not Changed";
}
}else{
return "Something Went Wrong, Password Not Changed";
}
}else{
return "Wrong Old Password";
}
}
When i click on the update button in my reset password page, i am getting the following error for my new password confirmation field: Unable to access an error message corresponding to your field name Confirm Password.()
please help!
1) there are two pipe signs near required||md5
$this->form_validation->set_rules('cnew_password','Confirm Password','trim|required||md5');
change it to
$this->form_validation->set_rules('cnew_password','Confirm Password','trim|required|md5');
2) changing input to md5 at this stage is not good.
You have to use password_hash function.
Read More >> http://php.net/manual/en/function.password-hash.php
3) You forgot to load model. $this->load->model('customer_model');

CodeIgniter login system using md5()

I am new in CodeIgniter and using CodeIgniter_2.1.3. I am following NETTUTS CodeIgniter tutorial. I want to develop a login system with codeIgniter which works well without md5() function [without encrypted password] . Then I create new table with encrypted password using md5() function. Then login code doesn't work. My code is ::
view/login_form.php
<?php
// form design
echo form_open("login/validate") . "<br/>";
echo form_input("username", "Username") . "<br/> <br/>";
echo form_password("password", "password") . "<br/> <br/>";
echo form_submit("submit", "Login") . "<Br/> <Br/>";
echo anchor("login/sign_up", "Create Account");
?>
controllers/login.php
<?php
class Login extends CI_Controller {
function index() { // function of loading login page
$data['main_content'] = "login_form"; // name of login page
$this->load->view("includes/templet", $data);
}
function validate() { // form validation
$this->load->model("membership_model"); // load "membership_model"
$query = $this->membership_model->validate_user(); // check validation
if( $query ) { // if data found
$data = array( // value which is to be inserted into session
"username" => $this->input->post("username"),
"is_logged_in" => true
);
$this->session->set_userdata($data); // insert value into session
redirect("site/members_area"); // go to predefined page
}
else {
// if data not found then go to login_form page
$this->index();
}
}
// create account
function sign_up() {
$data['main_content'] = "sign_up";
$this->load->view("includes/templet", $data);
}
// insert data into database
function create_member() {
$this->load->library("form_validation"); // load form_validation library
$this->form_validation->set_rules("username", "Username", "trim|required");
$this->form_validation->set_rules("password", "Enter Password", "trim|required|min_length[4]|max_length[32]");
$this->form_validation->set_rules("re_password", "Confirm password", "trim|required|matches[password]");
$this->form_validation->set_rules("email", "Email Address", "trim|required|valid_email");
if( $this->form_validation->run() == FALSE ) {
$this->load->view("sign_up");
}
else {
$this->load->model("membership_model");
if( $query = $this->membership_model->create_member() ) {
// redirect("site/members_area");
$data['main_content'] = "signup_success";
$this->load->view("includes/templet", $data);
}
else {
$this->load->view("sign_up");
}
}
}
}
?>
model/membership_model
<?php
class Membership_model extends CI_Model {
function validate_user() {
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get("user");
if( $query->num_rows == 1 ) {
return true;
}
}
function create_member() {
$new_member_insert_data = array(
'username' => $this->input->post("username"),
'password' => md5($this->input->post("password")),
'email' => $this->input->post("email")
);
$insert = $this->db->insert("user", $new_member_insert_data);
return true;
}
}
?>
I think the column "Password" in your table is less than varchar(32), md5 requires 32 varchar type.
For md5 password
check the data base field, because md5 generate 32 charactors.. so change the table field to varchar(32)
$data=array(
'password' => md5($this->input->post('password')),
);
Just change this statement from
if( $query->num_rows == 1 )
to
if( $query->num_rows() == 1 )
that row() in your
model/membership_model.php
It works

Resources