Forgot password function not working in CodeIgniter

久未见 提交于 2019-12-11 04:39:48

问题


Good day! I'm trying to make a forgot password function in the CodeIgniter framework but I'm getting 2 errors when i try to send the e-mail.

Some database info (I'm using phpMyAdmin):

Db name: kadokado
Db table name: users
Db email column: email
Db password column: wachtwoord

My controller file (Auth.php) :

    <?php

    class Auth extends CI_Controller{



 public function forgot()
    {

        $this->form_validation->set_rules('email', 'Email', 'required|valid_email'); 

        if($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header');
            $this->load->view('forgot');
            $this->load->view('templates/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', 'We hebben dit email adres niet kunnen vinden');
                redirect(site_url().'auth/login');
            }   

            if($userInfo->status != $this->status[1]){ //if status is not approved
                $this->session->set_flashdata('flash_message', 'Your account is not in approved status');
                redirect(site_url().'auth/login');
            }

            //build token 

            $token = $this->user_model->insertToken($userInfo->id);                    
            $qstring = $this->base64url_encode($token);                      
            $url = site_url() . 'auth/reset_password/token/' . $qstring;
            $link = '<a href="' . $url . '">' . $url . '</a>'; 

            $message = '';                     
            $message .= '<strong>A password reset has been requested for this email account</strong><br>';
            $message .= '<strong>Please click:</strong> ' . $link;             
            echo $message; //send this through mail
            exit;

        }

    }

public function reset_password()
    {
        $token = $this->base64url_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 is invalid or expired');
            redirect(site_url().'auth/login');
        }            
        $data = array(
            'voornaam'=> $user_info->voornaam, 
            'email'=>$user_info->email,                
            'token'=>base64_encode($token)
        );

        $this->form_validation->set_rules('wachtwoord', 'Wachtwoord', 'required|min_length[5]');
        $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required|matches[wachtwoord]');              

        if ($this->form_validation->run() == FALSE) {   
            $this->load->view('templates/header');
            $this->load->view('reset_password', $data);
            $this->load->view('templates/footer');
        }else{

            $this->load->library('wachtwoord');                 
            $post = $this->input->post(NULL, TRUE);                
            $cleanPost = $this->security->xss_clean($post);                
            $hashed = $this->password->create_hash($cleanPost['wachtwoord']);                
            $cleanPost['wachtwoord'] = $hashed;
            $cleanPost['user_id'] = $user_info->id;
            unset($cleanPost['passconf']);                
            if(!$this->user_model->updatePassword($cleanPost)){
                $this->session->set_flashdata('flash_message', 'Er is iets foutgegaan');
            }else{
                $this->session->set_flashdata('flash_message', 'Uw wachtwoord is geupdate, u kunt nu inloggen');
            }
            redirect(site_url().'auth/login');                
        }
    }


}

My model file (User_Model.php) :

    <?php


class user_model extends CI_model {


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 getUserInfo($user_id)
    {
        $q = $this->db->get_where('users', array('user_id' => $user_id), 1);  
        if($this->db->affected_rows() > 0){
            $row = $q->row();
            return $row;
        }else{
            error_log('no user found getUserInfo('.$user_id.')');
            return 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 . $user_id;

    }

    public function isTokenValid($token)
    {
       $tkn = substr($token,0,30);
       $uid = substr($token,30);      

        $q = $this->db->get_where('tokens', array(
            'tokens.token' => $tkn, 
            'tokens.user_id' => $uid), 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;
        }

    }    



}

?>

My view file (reset_password.php) :

 <div class="col-lg-4 col-lg-offset-4">
    <h2>Reset your password</h2>
    <h5>Hello <span><?php echo $firstName; ?></span>, Voer uw wachtwoord 2x in aub</h5>     
<?php 
    $fattr = array('class' => 'form-signin');
    echo form_open(site_url().'auth/reset_password/token/'.$token, $fattr); ?>
    <div class="form-group">
      <?php echo form_password(array('name'=>'wachtwoord', 'id'=> 'wachtwoord', 'placeholder'=>'Wachtwoord', 'class'=>'form-control', 'value' => set_value('wachtwoord'))); ?>
      <?php echo form_error('password') ?>
    </div>
    <div class="form-group">
      <?php echo form_password(array('name'=>'passconf', 'id'=> 'passconf', 'placeholder'=>'Confirm Password', 'class'=>'form-control', 'value'=> set_value('passconf'))); ?>
      <?php echo form_error('passconf') ?>
    </div>
    <?php echo form_hidden('user_id', $user_id);?>
    <?php echo form_submit(array('value'=>'Reset Password', 'class'=>'btn btn-lg btn-primary btn-block')); ?>
    <?php echo form_close(); ?>

</div>

And these are the errors I'm getting:

    A PHP Error was encountered

Severity: Notice

Message: Undefined property: Auth::$user_model

Filename: controllers/Auth.php

Line Number: 123

Backtrace:

File: /home/ubuntu/workspace/application/controllers/Auth.php
Line: 123
Function: _error_handler

File: /home/ubuntu/workspace/index.php
Line: 315
Function: require_once

2nd error:

    A PHP Error was encountered

Severity: Error

Message: Call to a member function getUserInfoByEmail() on a non-object

Filename: controllers/Auth.php

Line Number: 123

Backtrace:

I have absolutely no clue what I'm doing wrong and I hope someone can help me. Thanks!


回答1:


Load user model in auth controller. You can load it in constructor or in the function.

class Auth extends CI_Controller{

function __construct(){
    parent::__construct();
    $this->load->model('user_model');  // load user model
}

public function forgot(){
// your code
}

In Function

class Auth extends CI_Controller{
    public function forgot(){
        $this->load->model('user_model'); // load user model
        // your code
    }

Not tested




回答2:


You need to make sure that the user_model class is loaded from the controller. Like so:

class Auth extends CI_Controller {
    function __construct() {
        $this->load->model('user_model');
    }
}

And be sure that you have the spelling/capitalization correct in the model class.

class User_Model extends CI_Model {
    // rest of code
}



回答3:


@frodo again.

First Error : in your controller code, you need to initialize model first than only you can use the model property.

public function forgot(){
    // Changes required
    $this->load->model('user_model');
    $userInfo = $this->user_model->getUserInfoByEmail($clean);
}

Second Error :

if($userInfo->status != $this->status[1]){ 
      $this->session->set_flashdata('flash_message', 'Your account is not in approved status');
      redirect(site_url().'auth/login');
}

How you get the value of $this->status[1] variable. You can simply use if($userInfo->status != true).

Please change this code and let me know if you have any error.



来源:https://stackoverflow.com/questions/44547510/forgot-password-function-not-working-in-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!