Добрый день! Я пытаюсь сделать функцию забытого пароля в рамках CodeIgniter, но у меня возникают 2 ошибки при попытке отправить электронное письмо.
Некоторая информация о базе данных (я использую phpMyAdmin):
Db name: kadokado Db table name: users Db email column: email Db password column: wachtwoord
Мой файл контроллера (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'); } } }
-<?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'); } } }
с<?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'); } } }
Мой файл модели (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('Ym-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('Ym-d'); $todayTS = strtotime($today); if($createdTS != $todayTS){ return false; } $user_info = $this->getUserInfo($row->user_id); return $user_info; }else{ return false; } } } ?>
Мой файл просмотра (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>
И это ошибки, которые я получаю:
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
Вторая ошибка:
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:
Я абсолютно не понимаю, что я делаю неправильно, и я надеюсь, что кто-то может мне помочь. Благодаря!
Загрузите модель пользователя в контроллер auth. Его можно загрузить в конструкторе или в функции.
class Auth extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->model('user_model'); // load user model } public function forgot(){ // your code }
В функции
class Auth extends CI_Controller{ public function forgot(){ $this->load->model('user_model'); // load user model // your code }
Не испытано
Вы должны убедиться, что класс user_model загружен из контроллера. Вот так:
class Auth extends CI_Controller { function __construct() { $this->load->model('user_model'); } }
И убедитесь, что у вас правильная орфография / капитализация в классе модели.
class User_Model extends CI_Model { // rest of code }
@frodo снова.
Первая ошибка: в коде контроллера вам нужно сначала инициализировать модель, а только использовать свойство модели.
public function forgot(){ // Changes required $this->load->model('user_model'); $userInfo = $this->user_model->getUserInfoByEmail($clean); }
Вторая ошибка:
if($userInfo->status != $this->status[1]){ $this->session->set_flashdata('flash_message', 'Your account is not in approved status'); redirect(site_url().'auth/login'); }
Как вы получаете значение переменной $this->status[1]
. Вы можете просто использовать if($userInfo->status != true)
.
Пожалуйста, измените этот код и сообщите мне, есть ли у вас какие-либо ошибки.