Need to update the users table password field on codeigniter - php

# table name is users#
## model name is user_model##
### controller name is get_password ###
issue - no change on the password , remain as old
> model(user_model)
public function updatePassword($email,$data)
{
$data1=array('password'=>$data);
$this->db->where('email','$email');
$this->db->update('users','password');
$success = $this->db->affected_rows();
if(!$success){
error_log('Unable to updatePassword');
return false;
}
return true;
}
> controller(get_password)
public function index($rs=FALSE)
{
$this->load->database();
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->model('user_model');
$this->load->library('session');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'password', 'required');
$this->form_validation->set_rules('passconf', 'password Confirmation', 'required|matches[password]');
if ($this->form_validation->run() == FALSE)
{
echo form_open();
$this->load->view('users/fpre');
}
else
{
$data = array(
'password' => md5($this->input->post('password')),
);
$email =array(
'email' =>$this->input->post('email')
);
$this->user_model->updatePassword($data,$email);
echo "Congratulations!";
}
}
it shows no error but the password is not updated remain same at users table..i can't find the problem is, please help me to find it out ..

Controller (get_password):
public function index() {
$this->load->database();
$this->load->helper(array('form', 'url'));
$this->load->library(array('form_validation', 'session'));
$this->load->model('user_model');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'Current password', 'required');
$this->form_validation->set_rules('newpassword', 'password', 'required');
$this->form_validation->set_rules('newpassconf', 'password Confirmation', 'required|matches[newpassword]');
$email = $this->input->post('email');
$success = false;
$msg = '';
if ($this->form_validation->run() !== FALSE) {
$password = md5($this->input->post('password'));
if ($this->user_model->checkPassword($email, $password)){
$newpassword = md5($this->input->post('newpassword'));
if ($this->user_model->updatePassword($email, $newpassword)){
$success = true;
}else{
$msg = 'Unable to updatePassword';
}
}else{
$msg = 'Incorrect password';
}
}
if ($success){
echo 'Congratulations!';
}else{
$this->load->view('users/fpre', array(
'email'=>$email,
'msg'=>$msg
));
}
}
Model (user_model):
public function checkPassword($email, $password) {
$users = $this->db->get_where('users', array('email'=>$email))->row();
return $users->password === $password;
}
public function updatePassword($email, $newpassword) {
$data = array('password' => $newpassword);
$this->db->where('email', $email)
->update('users', $data);
$success = $this->db->affected_rows();
if (!$success) {
error_log('Unable to updatePassword');
}
return $success;
}
View (users/fpre):
if ($msg){
echo 'Message: '.$msg;
}
echo form_open();
echo form_input('email', $email);
echo form_password('password');
echo form_password('newpassword');
echo form_password('newpassconf');
echo form_submit('', 'Enviar');
echo form_close();
Changes to compare:

Your model function shows the parameters are expected to be email and then password, but your controller is passing them through be other way around.
$this->user_model->updatePassword($data,$email);
Should be:
$this->user_model->updatePassword($email,$data);
I also believe the data needs to be passed differently. The where() function expects either where(field_name, value) or where(array(field_name => value)). Looking at your code, you seem to be mixing both of those.
Using set() should help with this too, so instead of
$data1=array('password'=>$data);
$this->db->where('email','$email');
$this->db->update('users','password');
Use:
$this->db->set($data);
$this->db->where($email);
$this->db->update('users');
Note: code untested.

I believe this line $this->db->update('users','password'); should be $this->db->update('users', $data);.
Right now you are not passing the password to the update function. You are passing the string "password".

Related

Use form_validation correctly in CodeIgniter

I have a registration system with CodeIgniter but currently I have no control on email and password. A user can register without putting email or a password.
I have an index() and a register_user function() in my Signup controller but the redirection is not working on success
At the moment I have the following code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Signup extends CI_Controller {
public function index()
{
if(!isset($this->session->userdata['sessiondata']['user_id']))
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
if ($this->form_validation->run() == FALSE)
{
$this->load->view('signup-view');
}
else
{
$this->load->view('home-view');
}
}else{
if (intval($this->session->userdata['sessiondata']['user_type']) == 1) {
redirect(base_url().'admin');
} else {
redirect(base_url().'home');
}
}
}
function register_user(){
$this->load->library('custom_u_id');
$data = array('user_id' => $this->custom_u_id->construct_id('USR'),
'name' => $_POST['name'],
'email' => $_POST['email'],
'password' => $_POST['password'],
);
$this->load->model('signup_model');
$user_details = $this->signup_model->register_user($data);
if (!empty($user_details)){
$user_data = array
(
'user_id' => $user_details['user_id'],
'email' => $user_details['email'],
'name' => $user_details['name'],
'user_type' => $user_details['user_type'],
);
$this->session->set_userdata('sessiondata',$user_data);
if (intval($user_details['user_type']) == 1) {
redirect(base_url().'admin');
} else {
redirect(base_url().'home');
}
} else{
redirect('login');
}
}// end of function login
}
Do I need to put the form_validation in my register_user function ? I've tried but the check doesn't work anymore...
I also have in my view the <?php validation_errors();?> function and the <?php form_open(base_url().'signup');?>
looking by your code, i think you want to put register_user() inside validation TRUE since the query is in that method.
so try to change your code to this :
public function index()
{
if(!isset($this->session->userdata['sessiondata']['user_id']))
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
if ($this->form_validation->run() == FALSE)
{
$this->load->view('signup-view');
}
else
{
$this->register_user();
}
}else{
if (intval($this->session->userdata['sessiondata']['user_type']) == 1) {
redirect(base_url().'admin');
} else {
redirect(base_url().'home');
}
}
}
and be sure your form action to like this :
<form action="<?=site_url('/signup/index');?>">

Message: Undefined variable: email under Controllers

I am getting Undefined Variable email under Controllers.
Controller : login.php
public function index() {
$this->load->view('bootstrap/header');
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->load->model('Login_db');
$is_exist = $this->Login_db->isEmailExist($email);
if ($is_exist) {
$this->form_validation->set_message('isEmailExist', 'Email Address Already Exists!');
return FALSE;
} else {
return TRUE;
}
$this->load->view('bootstrap/footer');
}
Model : login_db.php
public function isEmailExist($email) {
$this->db->select('user_id');
$this->db->where('email', $email);
$query = $this->db->get('login');
if ($query->num_rows() > 0) {
return TRUE;
} else {
return FALSE;
}
}
I have to check whether email exists are not.
before
$is_exist = $this->Login_db->isEmailExist($email);
add this (in case of a POST request)
$email = $this->input->post('email');
or this ((in case of a GET request)
$email = $this->input->get('email');
by checking your code i came to assume that you want to allow only the emails which is already not in table ? why have not you validated with is_unique like
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[login.email]');
or you can change the line as
$this->Login_db->isEmailExist($this->input->post('email'));
or you should define $email before passing it / calling the function
$email=$this->input->post('email');
for custom massaging :
$this->form_validation->set_rules( 'email', 'Email', 'required|valid_email|is_unique[login.email]', array( 'is_unique' => 'Email already exists' ) );
better you go through the manual
https://www.codeigniter.com/user_guide/libraries/form_validation.html
the var $email used here
$is_exist = $this->Login_db->isEmailExist($email); line 5 of index
is never isntanciate. You should instantiate it to avoir error.

PHP CodeIgniter: Login 404 Error 'Trying to get property 'email' of non-object'

I have recently starting following some coding tutorials for PHP CodeIgniter and I have run into a bit of a snag for my login and registration system. The registration works perfectly, accessing the database and creating accounts but there is a problem with my login code that I can not work my head around.
I receive the following error:
A PHP Error was encountered Severity: Notice
Message: Trying to get property 'email' of non-object
Filename: controllers/Auth.php
Line Number: 23
Backtrace:
File: /opt/lampp/htdocs/application/controllers/Auth.php Line: 23
Function: _error_handler
File: /opt/lampp/htdocs/index.php Line: 315 Function: require_once
The code for the following is:
<?php
class Auth extends CI_Controller{
public function login()
{
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[5]');
if($this->form_validation->run() == TRUE) {
$username = $_POST['username'];
$password = md5($_POST['password']);
//check user in db
$this->db->select('*');
$this->db->from('users');
$this->db->where(array('username'=>$username, 'password'=>$password));
$query = $this->db->get();
$user = $query->row();
if ($user->email){
$this->session->set_flashdata("success", "You are logged in.");
$_SESSION['user_logged'] = TRUE;
$_SESSION['username'] = $user->username;
//redirect to profile page
redirect("user/profile", "refresh");
} else {
$this->session->set_flashdata("error", "NO such account exists");
//redirect("auth/login", "refresh");
}
}
$this->load->view('login');
}
public function register()
{
if(isset($_POST['register'])) {
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[5]');
$this->form_validation->set_rules('password', 'Confirm Password', 'required|min_length[5]|matches[password]');
if($this->form_validation->run() == TRUE) {
//echo 'form validated';
//add user in database
$data = array(
'username'=>$_POST['username'],
'email'=>$_POST['email'],
'password'=> md5($_POST['password'])
);
$this->db->insert('users', $data);
$this->session->set_flashdata("success", "Your account has been registered");
redirect("auth/register", "refresh");
}
}
$this->load->view('register');
}
}
?>
Any help would be appreciated and if anymore code that I have used for this tutorial is needed for a solution, just let me know.
Thank you.
You will get that kindof error when the result object from the database is returning no rows hence an empty stdClass and thus you will not be able to access any properties. The correct way of doing this is to check that num_rows() is equal to 1 (e.g. there should only be one user with that name and password).
public function login() {
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[5]');
if ($this->form_validation->run() == TRUE) {
$username = $_POST['username'];
/**
* Do not md5 your passwords!
* Use password_hash and password_verify!!
*/
$password = md5($_POST['password']); // DO NOT MD5 your passwords!
//check user in db
// this should be in a model!
$this->db->select('*');
$this->db->from('users');
$this->db->where(array('username' => $username, 'password' => $password));
$query = $this->db->get();
if ($query->num_rows() == 1) {
$user = $query->row();
$this->session->set_flashdata("success", "You are logged in.");
$_SESSION['user_logged'] = TRUE;
$_SESSION['username'] = $user->username;
//redirect to profile page
redirect("user/profile", "refresh");
} else {
$this->session->set_flashdata("error", "NO such account exists");
//redirect("auth/login", "refresh");
}
}
$this->load->view('login');
}
Generally you should get into the habit of checking if num_rows() > 0 before ever using result() row() .etc. because you can never be 100% sure that the data will be returned.
For example:
//model
function get_users() {
$query = $this->db->get('users');
if ($query->num_rows() == 0) {
return null;
}
return $query->result();
}
// controller
function something() {
$users = $this->model->get_users();
if (is_null($users)) {
exit('no users');
}
print_r($users);
}

Registration with CodeIgniter Ion Auth

I am trying to register a user with Ion Auth, but the register() function does not seem to report any error messages. How does one register with Ion Auth? I've already read various tutorials like this one and this one (and the documentation), but they do not seem to be working.
function register()
{
// do not allow registration if logged in
if ($this->ion_auth->logged_in())
{
redirect('/');
}
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|callback_email_check');
$this->form_validation->set_rules('email2', 'Email Confirmation', 'trim|required|valid_email|matches[email]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|md5');
if ($this->form_validation->run() == FALSE)
{
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
$this->load->view('header');
$this->load->view('register', $this->data);
$this->load->view('footer');
}
else
{
$username = $this->input->post('email');
$password = $this->input->post('password');
$email = $username;
$additional_data = array(
'first_name' => $this->input->post('name'),
'last_name' => '',
);
if (!$this->ion_auth->email_check($email))
{
$group_name = 'users';
$uId = $this->ion_auth->register($username, $password, $email, $additional_data, $group_name);
if ($uId == FALSE)
{
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect("home/register", 'refresh');
}
else
{
redirect('/'); // registration success
}
}
}
}
function email_check($str)
{
if ($this->ion_auth->email_check($str))
{
$this->form_validation->set_message('email_check', 'This email is already registered.');
return FALSE;
}
return TRUE;
}

CodeIgniter Form Validation Error Redirect

I have the following controller, which works fine in terms of validating the form and displaying the error.
The user attempts to login from: http://mydomain.com/index.php/login
However, when the user enters the wrong credentials, it loads the login view properly (as it should) and displays the error "Invalid Login" properly, but the URI in the browser window shows:
http://mydomain.com/index.php/verify_login (as opposed to the one above).
How do I redirect after the failed validation to just ".../index.php/login"
Here is the code in question:
<?
class Login extends CI_Controller {
public function index()
{
$this->load->helper(array('form'));
$this->load->helper('url');
$this->load->view('login_page');
}
function verify_login()
{
$this->load->model('login_model','',TRUE);
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<label class="error">', '</label>');
$this->form_validation->set_rules('username', 'Login', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE)
{
//Field validation failed. User redirected to login page
$this->index();
}
else
{
//Go to private area
redirect('private_area', 'refresh');
}
}
function check_database($password)
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//query the database
$result = $this->login_model->login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'id' => $row->id,
'username' => $row->username
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', '<div class="alert alert-error">Invalid username or password</div>');
return false;
}
}
}
UPDATE: Cyrode's solution fixes that issue, but now it's not displaying the "Invalid Login" error message (set_message) from the check_database() function on loading the view. Any ideas what I am doing wrong here?
UPDATE 2:
Here you go:
class Login extends CI_Controller {
public function index()
{
$this->load->helper(array('form'));
$this->load->helper('url');
$this->load->view('login_page');
$this->load->model('login_model','',TRUE);
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<label class="error">', '</label>');
$this->form_validation->set_rules('username', 'Login', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE)
{
$this->load->view('login_page');
}
else
{
//Go to private area
redirect('private_area', 'refresh');
}
}
function check_database($password)
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//query the database
$result = $this->login_model->login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'id' => $row->id,
'username' => $row->username
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', '<div class="alert alert-error">Invalid username or password</div>');
return false;
}
}
}
Just do all of your form processing in the index() method.
public function index()
{
$this->load->model('login_model','',TRUE);
$this->load->library('form_validation');
$this->load->helper('url');
$this->form_validation->set_error_delimiters('<label class="error">', '</label>');
$this->form_validation->set_rules('username', 'Login', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if ($this->form_validation->run() == false)
{
$this->load->view('login_page');
}
else
{
redirect('private_area', 'refresh');
}
}
Then, make sure your form's action goes to login and not verify_login.
By the way, don't xss_clean password fields, because it may change their value, and your user will be left wondering why their perfectly-typed password isn't working. You should be hashing the password, anyway, which will eliminate security issues.

Categories