sending token to email in codeigniter - php

I'm working on a small application that can provide registering an account and sending token to complete registration to email.
I have everything working except sending emails with which I can't handle and I'm not sure how to do this. I'd really appreciat any help and explanations on how can I actually send an email instead of just displaying token in view.
There are 2 functions in which I want to send token via mail: register and forgot.
This is my Controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Main extends CI_Controller {
public $status;
public $roles;
function __construct(){
parent::__construct();
$this->load->model('User_model', 'user_model', TRUE);
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->status = $this->config->item('status');
$this->roles = $this->config->item('roles');
}
public function index()
{
if(empty($this->session->userdata['email'])){
redirect(site_url().'/main/login/');
}
/*front page*/
$data = $this->session->userdata();
$this->load->view('header');
$this->load->view('index', $data);
$this->load->view('footer');
}
public function ankieta()
{
$data = $this->session->userdata();
$this->load->view('ankieta/header');
$this->load->view('ankieta/ankieta', $data);
$this->load->view('ankieta/footer');
}
public function register()
{
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.gmail.com',
'smtp_port' => 465,
'smtp_user' => 'mymail#gmail.com',
'smtp_pass' => 'pass',
'mailtype' => 'html',
'charset' => 'utf-8'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->form_validation->set_rules('firstname', 'Imię', 'required');
$this->form_validation->set_rules('lastname', 'Nazwisko', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if ($this->form_validation->run() == FALSE) {
$this->load->view('header');
$this->load->view('register');
$this->load->view('footer');
}else{
if($this->user_model->isDuplicate($this->input->post('email'))){
$this->session->set_flashdata('flash_message', 'Podany adres email już istnieje');
redirect(site_url().'/main/login');
}else{
$clean = $this->security->xss_clean($this->input->post(NULL, TRUE));
$id = $this->user_model->insertUser($clean);
$token = $this->user_model->insertToken($id);
$qstring = base64_encode($token);
$url = site_url() . '/main/complete/token/' . $qstring;
$link = '' . $url . '';
$message = '';
$message .= '<strong>Dziekujemy za dokonanie rejestracji.</strong><br>';
$message .= '<strong>Aby dokończyć rejestrację przejdź na podany adres:</strong> ' . $link;
$to = $email;
$this->email->clear();
$this->email->from('whatever#c.com');
$this->email->to($to);
$this->email->subject('Thanks for registering');
$this->email->message($message);
if($this->email->send() === TRUE){
$this->session->set_flashdata('flash_message', 'Password reset done.');
redirect(site_url().'/main/login');
}else{
$this->session->set_flashdata('flash_message', 'Password reset fail.');
redirect(site_url().'/main/forgot');
}
};
}
}
protected function _islocal(){
return strpos($_SERVER['HTTP_HOST'], 'local');
}
public function complete()
{
$token = base64_decode($this->uri->segment(4));
$cleanToken = $this->security->xss_clean($token);
$user_info = $this->user_model->isTokenValid($cleanToken); //either false or array();
if(!$user_info){
$this->session->set_flashdata('flash_message', 'Token jest nieprawidłowy lub wygasł');
redirect(site_url().'/main/login');
}
$data = array(
'firstName'=> $user_info->first_name,
'lastName'=> $user_info->last_name,
'email'=>$user_info->email,
'user_id'=>$user_info->id,
'token'=>base64_encode($token)
);
$this->form_validation->set_rules('password', 'Hasło', 'required|min_length[5]');
$this->form_validation->set_rules('passconf', 'Potwierdź hasło', 'required|matches[password]');
if ($this->form_validation->run() == FALSE) {
$this->load->view('header');
$this->load->view('complete', $data);
$this->load->view('footer');
}else{
$this->load->library('password');
$post = $this->input->post(NULL, TRUE);
$cleanPost = $this->security->xss_clean($post);
$hashed = $this->password->create_hash($cleanPost['password']);
$cleanPost['password'] = $hashed;
unset($cleanPost['passconf']);
$userInfo = $this->user_model->updateUserInfo($cleanPost);
if(!$userInfo){
$this->session->set_flashdata('flash_message', 'Wystąpił problem ze zmianąTwoich danych');
redirect(site_url().'/main/login');
}
unset($userInfo->password);
foreach($userInfo as $key=>$val){
$this->session->set_userdata($key, $val);
}
redirect(site_url().'/main/index');
}
}
public function login()
{
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'Hasło', 'required');
if($this->form_validation->run() == FALSE) {
$this->load->view('header');
$this->load->view('login');
$this->load->view('footer');
}else{
$post = $this->input->post();
$clean = $this->security->xss_clean($post);
$userInfo = $this->user_model->checkLogin($clean);
if(!$userInfo){
$this->session->set_flashdata('flash_message', 'Logowanie nie powiodło się');
redirect(site_url().'/main/login');
}
foreach($userInfo as $key=>$val){
$this->session->set_userdata($key, $val);
}
redirect(site_url().'/main/index');
}
}
public function logout()
{
$this->session->sess_destroy();
redirect(site_url().'/main/login/');
}
public function forgot()
{
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if($this->form_validation->run() == FALSE) {
$this->load->view('header');
$this->load->view('forgot');
$this->load->view('footer');
}else{
$email = $this->input->post('email');
$clean = $this->security->xss_clean($email);
$userInfo = $this->user_model->getUserInfoByEmail($clean);
if(!$userInfo){
$this->session->set_flashdata('flash_message', 'Adres email nie istnieje');
redirect(site_url().'/main/login');
}
if($userInfo->status != $this->status[1]){ //if status is not approved
$this->session->set_flashdata('flash_message', 'Twoje konto nie zostało aktywowane');
redirect(site_url().'/main/login');
}
//build token
$token = $this->user_model->insertToken($userInfo->id);
$qstring = base64_encode($token);
$url = site_url() . '/main/reset_password/token/' . $qstring;
$link = '' . $url . '';
$message = '';
$message .= '<strong>Zmiana hasła</strong><br>';
$message .= '<strong>Aby dokonać zmiany hasła przejdź na podany adres:</strong> ' . $link;
echo $message;
exit;
}
}
public function reset_password()
{
$token = base64_decode($this->uri->segment(4));
$cleanToken = $this->security->xss_clean($token);
$user_info = $this->user_model->isTokenValid($cleanToken); //either false or array();
if(!$user_info){
$this->session->set_flashdata('flash_message', 'Token jest nieprawidłowy lub wygasł');
redirect(site_url().'/main/login');
}
$data = array(
'firstName'=> $user_info->first_name,
'lastName'=> $user_info->last_name,
'email'=>$user_info->email,
'user_id'=>$user_info->id,
'token'=>base64_encode($token)
);
$this->form_validation->set_rules('password', 'Hasło', 'required|min_length[5]');
$this->form_validation->set_rules('passconf', 'Potwierdź hasło', 'required|matches[password]');
if ($this->form_validation->run() == FALSE) {
$this->load->view('header');
$this->load->view('reset_password', $data);
$this->load->view('footer');
}else{
$this->load->library('password');
$post = $this->input->post(NULL, TRUE);
$cleanPost = $this->security->xss_clean($post);
$hashed = $this->password->create_hash($cleanPost['password']);
$cleanPost['password'] = $hashed;
unset($cleanPost['passconf']);
if(!$this->user_model->updatePassword($cleanPost)){
$this->session->set_flashdata('flash_message', 'Wystąpił błąd przy próbie zmiany hasła');
}else{
$this->session->set_flashdata('flash_message', 'Twoje hasło zostało zmienione. Możesz się zalogować');
}
redirect(site_url().'/main/login');
}
}
}
This is my model:
<?php
class User_model extends CI_Model {
public $status;
public $roles;
function __construct(){
// Call the Model constructor
parent::__construct();
$this->status = $this->config->item('status');
$this->roles = $this->config->item('roles');
}
public function insertUser($d)
{
$string = array(
'first_name'=>$d['firstname'],
'last_name'=>$d['lastname'],
'email'=>$d['email'],
'role'=>$this->roles[0],
'status'=>$this->status[0]
);
$q = $this->db->insert_string('users',$string);
$this->db->query($q);
return $this->db->insert_id();
}
public function isDuplicate($email)
{
$this->db->get_where('users', array('email' => $email), 1);
return $this->db->affected_rows() > 0 ? TRUE : FALSE;
}
public function insertToken($user_id)
{
$token = substr(sha1(rand()), 0, 30);
$date = date('Y-m-d');
$string = array(
'token'=> $token,
'user_id'=>$user_id,
'created'=>$date
);
$query = $this->db->insert_string('tokens',$string);
$this->db->query($query);
return $token;
}
public function isTokenValid($token)
{
$q = $this->db->get_where('tokens', array('token' => $token), 1);
if($this->db->affected_rows() > 0){
$row = $q->row();
$created = $row->created;
$createdTS = strtotime($created);
$today = date('Y-m-d');
$todayTS = strtotime($today);
if($createdTS != $todayTS){
return false;
}
$user_info = $this->getUserInfo($row->user_id);
return $user_info;
}else{
return false;
}
}
public function getUserInfo($id)
{
$q = $this->db->get_where('users', array('id' => $id), 1);
if($this->db->affected_rows() > 0){
$row = $q->row();
return $row;
}else{
error_log('no user found getUserInfo('.$id.')');
return false;
}
}
public function updateUserInfo($post)
{
$data = array(
'password' => $post['password'],
'last_login' => date('Y-m-d h:i:s A'),
'status' => $this->status[1]
);
$this->db->where('id', $post['user_id']);
$this->db->update('users', $data);
$success = $this->db->affected_rows();
if(!$success){
error_log('Unable to updateUserInfo('.$post['user_id'].')');
return false;
}
$user_info = $this->getUserInfo($post['user_id']);
return $user_info;
}
public function checkLogin($post)
{
$this->load->library('password');
$this->db->select('*');
$this->db->where('email', $post['email']);
$query = $this->db->get('users');
$userInfo = $query->row();
if(!$this->password->validate_password($post['password'], $userInfo->password)){
error_log('Unsuccessful login attempt('.$post['email'].')');
return false;
}
$this->updateLoginTime($userInfo->id);
unset($userInfo->password);
return $userInfo;
}
public function updateLoginTime($id)
{
$this->db->where('id', $id);
$this->db->update('users', array('last_login' => date('Y-m-d h:i:s A')));
return;
}
public function getUserInfoByEmail($email)
{
$q = $this->db->get_where('users', array('email' => $email), 1);
if($this->db->affected_rows() > 0){
$row = $q->row();
return $row;
}else{
error_log('no user found getUserInfo('.$email.')');
return false;
}
}
public function updatePassword($post)
{
$this->db->where('id', $post['user_id']);
$this->db->update('users', array('password' => $post['password']));
$success = $this->db->affected_rows();
if(!$success){
error_log('Unable to updatePassword('.$post['user_id'].')');
return false;
}
return true;
}
}
I'm passing $message variable to see if token works. Also while people are registering they have to input their email address. So I want tokens to go directly to emails they input in register form.
Thank you for help.

Configure your localhost mail settings as well
XAMPP
WAMP
Try This
$this->load->library('email');
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.gmail.com',
'smtp_port' => 465,
'smtp_user' => 'mymail#gmail.com',
'smtp_pass' => 'pass',
'mailtype' => 'html',
'charset' => 'utf-8'
);
$this->email->initialize($config);
$this->email->set_newline("\r\n");
$clean = $this->security->xss_clean($this->input->post(NULL, TRUE));
$id = $this->user_model->insertUser($clean);
$token = $this->user_model->insertToken($id);
$qstring = base64_encode($token);
$url = site_url() . '/main/complete/token/' . $qstring;
$link = 'Activation Link';
$message = '';
$message .= '<strong>Dziekujemy za dokonanie rejestracji.</strong><br>';
$message .= '<strong>Aby dokończyć rejestrację przejdź na podany adres:</strong> '. $link;
$toEmail = $this->input->post('email');
$to = $toEmail; # undefine
$this->email->clear();
$this->email->from('whatever#c.com');
$this->email->to($to);
$this->email->subject('Thanks for registering');
$this->email->message($message);
if(!$this->email->send())
{
echo "fail <br>";
echo $this->email->print_debugger();
/*$this->session->set_flashdata('flash_message', 'Password reset fail.');
redirect(site_url().'/main/register');*/
}
else
{
echo "Pass <br>";
/* $this->session->set_flashdata('flash_message', 'Password reset done.');
redirect(site_url().'/main/login');*/
}

Since I don't see you attempting to send an email anywhere, this is how you send an email using CI's built in library.
//load ci email library
public function send_registration_email()
{
$this->load->library('email');
$link = '' . $url . '';
$message = $link;
$to = 'some#email.com';
$this->email->clear();
$this->email->from('whatever#c.com');
$this->email->to($to);
$this->email->subject('Thanks for registering');
$this->email->message($message);
if($this->email->send() === TRUE){ //Sends a plain text email containing the link
//something
}else{
//something else
}
}

Related

login api with email, password or mobile number,password in codeigniter

I am trying to create an api which enables login for email id and password or mobile number and password in codeigniter but i was unable to do both i don't know the error. Here is my code of controller
Controller code
public function signin()
{
$this->default_file();
$responseData = array();
if(!empty($_POST['username']))
{
$userData = array();
$get_number = $this->validate_mobile($_POST['username']);
if(!empty($get_number))
{
$userData['usermob'] = $_POST['username'];
}
else
{
$userData['useremail'] = $_POST['username'];
}
$userData['userpass'] = $_POST['userpass'];
$userSignIn = $this->apm->signin($userData);
if((((!empty($userSignIn['id'])) && (!empty($userSignIn['useremail']))) ||((!empty($userSignIn['id'])) && (!empty($userSignIn['usermob'])))))
{
$session_data = array('id'=> $userSignIn['id'], 'logged_in'=> true);
$this->session->set_userdata('userLoggedIn', $session_data);
$userDetails = array();
$userDetails['id'] = $userSignIn['id'];
$getUserDetails = $this->apm->getUserDetails($userDetails);
$responseData['id'] = $getUserDetails['result']['u_id'];
$responseData['username'] = $getUserDetails['result']['username'];
$responseData['useremail'] = $getUserDetails['result']['useremail'];
$responseData['usermob'] = $getUserDetails['result']['usermob'];
$responseData['userlocation'] = $getUserDetails['result']['userlocation'];
$responseData['device_token'] = $getUserDetails['result']['device_token'];
$responseData['device_name'] = $getUserDetails['result']['device_name'];
$responseArray = array(
'apiName' => 'signin',
'version' => '1.0.0',
'responseCode' => 200,
'responseMessage' => 'logged in successfully',
'responseData' => $responseData
);
}
else
{
$responseArray = array(
'apiName' => 'signin',
'version' => '1.0.0',
'responseCode' => 204,
'responseMessage' => "Email or Passwor is incorrect.",
'responseData' => null//$responseData
);
}
}
else
{
$responseArray = array(
'apiName' => 'signin',
'version' => '1.0.0',
'responseCode' => 204,
'responseMessage' => "Sorry, please provide your input details.",
'responseData' => null//$responseData
);
}
echo json_encode($responseArray);
die();
}
My modal Code is here
public function signin($userData)
{
$arrData = array();
if(!empty($userData['useremail']) || !empty($userData['usermob']))
{
if(!empty($userData['useremail']))
{
$where = "useremail='".$userData['useremail']."'";
}
if(!empty($userData['usermob']))
{
$where = "usermob='".$userData['usermob']."'";
}
$this->db->select('*');
$this->db->from('users');
$this->db->where($where);
$result = $this->db->get()->result_array();
if(!empty($result))
{
if(!empty($userData['useremail']))
{
if(($userData['useremail']) && ($userData['userpass']))
{
$where = "useremail='".$userData['useremail']."' AND userpass='".$userData['userpass']."'";
$this->db->select('*');
$this->db->from('users');
$this->db->where($where);
$res = $this->db->get()->result_array();
if(!empty($res))
{
$arrData['id'] = $res[0]['u_id'];
$arrData['useremail'] = $res[0]['useremail'];
}
else
{
$arrData['errorLogin'] = 'Incorrect email or password';
}
}
}
if(!empty($userData['usermob']))
{
if(($userData['usermob']) && ($userData['userpass']))
{
$where = "usermob='".$userData['usermob']."' AND userpass='".$userData['userpass']."'";
$this->db->select('*');
$this->db->from('users');
$this->db->where($where);
$res = $this->db->get()->result_array();
if(!empty($res))
{
$arrData['id'] = $res[0]['u_id'];
$arrData['usermob'] = $res[0]['usermob'];
}
else
{
$arrData['errorLogin'] = 'Incorrect email or password';
}
}
}
}
else
{
$arrData['error'] = 'Please Enter username and password';
}
}
return $arrData;
}
I was trying to login with email and mobile number but my code gives only one access either with email or with mobile. i want help so that i can login with email and mobile number both.
I have tested this code using Postman, hope it can help:
public function signin($userData)
{
//get the data using useremail and userpass
$this->db->where('useremail', $userData['useremail']);
$this->db->where('userpass', $userData['userpass']);
$result = $this->db->get('users')->result_array();
//if there's no result, get the data using usermob and userpass
if (!$result) {
$this->db->where('usermob', $userData['usermob']);
$this->db->where('userpass', $userData['userpass']);
$result = $this->db->get('users')->result_array();
}
//if there's still no result, the username or password was incorect
if (!$result) {
$result = 'Wrong Username or Password';
}
return $result;
}

how to verify the hashed password?

I am using CodeIgniter framework.
Below is the function contained in the Signup.php controller.
public function _hash_string($str){
$hashed_string = password_hash($str, PASSWORD_BCRYPT);
return $hashed_string;
}
public function _verify_hash($text, $hashed_string){
$result = password_verify($text, $hashed_string);
return result; //TRUE OR FALSE
}
public function index()
{
if($this->input->post('newuser') == 1)
{
$user = new Users_model();
$user->username = $this->input->post('username');
$user->email = $this->input->post('email');
$pass= $this->input->post('password');
$hashed_pass = $this ->_hash_string($pass);
$user->password = $hashed_pass;
$user->account_status = 1;
$user->user_role = $this->input->post('user_role');
$id = $this->usermodel->insert($user);
}else{
$this->load->view('signup-page');
}
I've successfully hashed the user's password. How can I verify them?
Below is the function contained in the Login.php controller.
public function index()
{
if($this->input->post('login') == 1)
{
$user = new Users_model();
$user->email = $this->input->post('email');
$user->password = $this->input->post('password');
$user->user_role = $this->input->post('user_role');
$results = $this->usermodel->login($user);
if(count($results) > 0)
{
foreach($results as $row)
{
$session_array = array(
"id" => $row['id'],
"username" => $row['username'],
"email" => $row['email'],
"password" => $row['password'],
"account_status" => $row['account_status'],
"user_role" => $row['user_role']
);
$this->session->set_userdata($session_array);
$url = base_url() . "home?login=success";
redirect($url, "refresh");
}
}else{
$url = base_url() . "login?login=failed";
redirect($url, "refresh");
}
}else{
$this->load->view('login-page');
}
}
And here is the Users_model.php model.
function login($user){
$conditions = array(
"email" => $user->email,
"password" => $user->password,
"user_role" => $user->user_role,
"account_status" => 1,
);
$this->db->select('*');
$this->db->from('users');
$this->db->where($conditions);
$rs= $this->db->get();
return $rs->result_array();
}
What should I do to properly log the user in?
You can't compare password in mysql. because hashed using php, you have to use php function to compare password.
function login($user){
$conditions = array(
"email" => $user->email,
//"password" => $user->password,
"user_role" => $user->user_role,
"account_status" => 1,
);
$this->db->select('*');
$this->db->from('users');
$this->db->where($conditions);
$rs= $this->db->get();
if(!empty($rs)) {
$result_array = $rs->row_array();
$controllerInstance = & get_instance();
if($controllerInstance->_verify_hash($user->password,$result_array['password']) == TRUE) {
return $result_array;
}
}
return false;
}
use get instance to access controller.
$controllerInstance = & get_instance();
$controllerData = $controllerInstance->_verify_hash();
Hope this helps. updated after zaph comment

Session Doesn't work in codeigniter

In my project, session is work fine before few days.But now it doesn't work. i can't find the error. plsease help me. it displays error called Severity: Notice
Message: Undefined index: firstname
Filename: user_include/header.php
Line Number: 5
A PHP Error was encountered
Severity: Notice
Message: Undefined
index: id
Filename: user_include/header.php
Line Number: 7
controller
/ Check for user login process
public function user_login_process() {
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
if(isset($this->session->userdata['logged_in'])){
//$this->load->view('admin_page');
$this->home();
}else{
$this->load->view('user_site/login_form');
}
} else {
$data = array(
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
);
$result = $this->login_database->login($data);
if ($result == TRUE) {
$email = $this->input->post('email');
$result = $this->login_database->read_user_information($email);
if ($result != false) {
$session_data = array(
'firstname' => $result[0]->firstname,
'email' => $result[0]->email,
'id' => $result[0]->id,
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->load->view("user_include/header");
$this->load->view('user_site/index');
}
} else {
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('user_site/login_form', $data);
}
}
}
// Logout
public function logout() {
// Removing session data
$sess_array = array(
'email' => ''
);
$this->session->unset_userdata('logged_in', $sess_array);
$data['message_display'] = 'Successfully Logout';
$this->load->view('user_site/login_form', $data);
}
}
?>
model
// Read data using username and password
public function login($data) {
$condition = "email =" . "'" . $data['email'] . "' AND " . "password =" . "'" . $data['password'] . "'";
$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 true;
} else {
return false;
}
}
// Read data from database to show data in admin page
public function read_user_information($email) {
$condition = "email =" . "'" . $email . "'";
$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;
}
}
}
?>
view
<?php
if (isset($this->session->userdata['logged_in'])) {
$firstname = ($this->session->userdata['logged_in']['firstname']);
$email = ($this->session->userdata['logged_in']['email']);
$id = ($this->session->userdata['logged_in']['id']);
} else {
header("location: login");
}
the error is in you user_include/header.php , check the id and firstname are set before you echo them out.
In your model replace following code by given code:
public function read_user_information($email) {
$condition = "email =" . "'" . $email . "'";
$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;
}
}
To
public function read_user_information($email) {
$this->db->select('firstname, email, id');
$this->db->from('user');
$this->db->where('email',$email);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->row_array();
} else {
return false;
}
}
In your controller replace following code by given
$email = $this->input->post('email');
$result = $this->login_database->read_user_information($email);
if ($result != false) {
$session_data = array(
'firstname' => $result[0]->firstname,
'email' => $result[0]->email,
'id' => $result[0]->id,
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->load->view("user_include/header");
$this->load->view('user_site/index');
}
To
$email = $this->input->post('email');
$user_details = $this->login_database->read_user_information($email);
if ($user_details != false) {
// Add user data in session
$this->session->set_userdata('logged_in', $user_details);
$this->load->view("user_include/header");
$this->load->view('user_site/index');
}
In view, replace your code by following:
<?php
$user_details = $this->session->userdata['logged_in']);
if ($user_details != "") {
$firstname = $user_details['firstname'];
$email = $user_details['email'];
$id = $user_details['id'];
} else {
header("location: login");
}

password_hash not updating when submit form

When I submit my form if password fields are submitted it should update the password else if empty does not update password.
I cannot seem to get the password_hash to update very strange. I can create new users fine with it but not update there password.
All other post are working fine update fine.
Not sure why password not updating? How am I able to fix issue thanks in advance.
<?php
class Model_user extends CI_Model {
public function edit_user($user_id, $data) {
$data = array(
'username' => $data['username'],
'user_group_id' => $data['user_group_id'],
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'image' => $data['image'],
'status' => $data['status']
);
$this->db->set($data);
$this->db->where('user_id', $user_id);
$this->db->update($this->db->dbprefix . 'user');
if ($data['password']) {
$options = [
'cost' => 11,
'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
];
$data = array(
'password' => password_hash($_POST['password'], $options)
);
$this->db->set($data);
$this->db->where('user_id', $user_id);
$this->db->update($this->db->dbprefix . 'user');
}
}
}
Controller
<?php
class Users extends MY_Controller {
public function __construct() {
parent::__construct();
$this->load->model('admin/user/model_user');
}
public function index() {
$this->get_form();
}
public function update() {
$this->form_validation->set_rules('username', 'Username', 'required');
if ($this->form_validation->run($this) == FALSE) {
$this->get_form();
} else {
$this->model_user->edit_user($this->uri->segment(4), $_POST);
redirect('admin/user');
}
}
public function get_form() {
$data['title'] = "Users";
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => 'Home',
'href' => site_url('admin/dashboard')
);
$data['breadcrumbs'][] = array(
'text' => "Users",
'href' => site_url('admin/user')
);
$user_info = $this->model_user->get_user($this->uri->segment(4));
if (isset($_POST['username'])) {
$data['username'] = $_POST['username'];
} elseif (!empty($user_info)) {
$data['username'] = $user_info['username'];
} else {
$data['username'] = '';
}
if (isset($_POST['user_group_id'])) {
$data['user_group_id'] = $_POST['user_group_id'];
} elseif (!empty($user_info)) {
$data['user_group_id'] = $user_info['user_group_id'];
} else {
$data['user_group_id'] = '';
}
$this->load->model('admin/user_group/user_group_model');
$data['user_groups'] = $this->user_group_model->get_user_groups();
if (isset($_POST['password'])) {
$data['password'] = $_POST['password'];
} else {
$data['password'] = '';
}
if (isset($_POST['confirm'])) {
$data['confirm'] = $_POST['confirm'];
} else {
$data['confirm'] = '';
}
if (isset($_POST['firstname'])) {
$data['firstname'] = $_POST['firstname'];
} elseif (!empty($user_info)) {
$data['firstname'] = $user_info['firstname'];
} else {
$data['firstname'] = '';
}
if (isset($_POST['lastname'])) {
$data['lastname'] = $_POST['lastname'];
} elseif (!empty($user_info)) {
$data['lastname'] = $user_info['lastname'];
} else {
$data['lastname'] = '';
}
if (isset($_POST['email'])) {
$data['email'] = $_POST['email'];
} elseif (!empty($user_info)) {
$data['email'] = $user_info['email'];
} else {
$data['email'] = '';
}
if (isset($_POST['image'])) {
$data['image'] = $_POST['image'];
} elseif (!empty($user_info)) {
$data['image'] = $user_info['image'];
} else {
$data['image'] = '';
}
$this->load->model('admin/tool/model_tool_image');
if (isset($_POST['image']) && is_file(FCPATH . 'image/catalog/' . $_POST['image'])) {
$data['thumb'] = $this->model_tool_image->resize($_POST['image'], 100, 100);
} elseif (!empty($user_info) && $user_info['image'] && is_file(FCPATH . 'image/catalog/' . $user_info['image'])) {
$data['thumb'] = $this->model_tool_image->resize($user_info['image'], 100, 100);
} else {
$data['thumb'] = $this->model_tool_image->resize('no_image.png', 100, 100);
}
$data['placeholder'] = $this->model_tool_image->resize('no_image.png', 100, 100);
if (isset($_POST['status'])) {
$data['status'] = $_POST['status'];
} elseif (!empty($user_info)) {
$data['status'] = $user_info['status'];
} else {
$data['status'] = 0;
}
$this->load->view('template/user/user_form_view', $data);
}
}
Take a closer look at the edit_user function. You receive $data but you immediately overwrite it. Please note that you don't set a password key to the newly created array. Then you check if ($data['password']) but that will never be true therefore the update will never be done.
There is a problem in your password_hash($_POST['password'], $options).
You passed $_POST['password'] instead of $data['password'].
It took me a while to figure it out I needed to create another variable out side of the if statement in my model like below and then was able to update if new password present.
All working now.
$input_password = $this->input->post('password');
if ($input_password) {
$password = password_hash($input_password, PASSWORD_BCRYPT);
$data_password = array(
'password' => $password
);
$this->db->where('user_id', $user_id);
$this->db->update($this->db->dbprefix . 'user', $data_password);
}

select and where condition in codeigniter

In this coding iam checking the whether email id is present in database.After that i need to change password.
function user_password($input, $serviceName){
$ipJson = json_encode($input);
$updateArray = array(
'email' => $input['email'],
'password' => md5($input['password']),
'user_modified_date' => date('Y-m-d H:i:s'),
);
$this->db->where('email', $input['email']);
$update = $this->db->update('users', $updateArray);
if ($update) {
$data['message'] = 'email id is present';
$status = $this->clamo_lib->return_status('success', $serviceName, $data, $ipJson);
}
else {
$data['message'] = 'Error In Updating Please Check Your Email ID';
$status = $this->clamo_lib->return_status('error', $serviceName, $data, $ipJson);
}
return $status;
}
if email is present in db i need to get "email id is present" message else i need to get "error"message.how i need to check the condition.
As you need to check that email address already in use or not.
So in model
$this->db->where("email",$input['email']);
$query = $this->db->get("users");
if($query->num_rows()>0){
$status['message'] = 'Email Already Exist';
}
function user_password($input, $serviceName)
{
$ipJson = json_encode($input);
$updateArray = array(
'email' => $input['email'],
'password' => md5($input['password']),
'user_modified_date' => date('Y-m-d H:i:s'),
);
$this->db->where('email', $input['email']);
$update = $this->db->update('users', $updateArray);
if ($update==TRUE)
{
$data['message'] = 'email id is present';
$status = $this->clamo_lib->return_status('success', $serviceName, $data, $ipJson);
}
else
{
$data['message'] = 'Error In Updating Please Check Your Email ID';
$status = $this->clamo_lib->return_status('error', $serviceName, $data, $ipJson);
}
return $status;
}
//change your update function in model something like this:
function update('users',$updatearray)
{
if(is_array($dataarray))
{
$this->db->trans_start();
$this->db->where('email',$this->input->post('email'));
$this->db->update('table',$updatearray);
$this->db->trans_complete();
return TRUE;
}
else
{
return FALSE
}
}

Categories