Trying to get property 'email' of non-object - php

I am getting following error from my code written in Codeigniter when i enter a wrong E-mail.
A PHP Error was encountered Severity: Notice
Message: Trying to get property 'email' of non-object
Filename: controllers/forms.php
Line Number: 26
Backtrace:
File:
E:\Software\XAMPP\xampp\htdocs\ciauth\application\controllers\forms.php
Line: 26 Function: _error_handler
File: E:\Software\XAMPP\xampp\htdocs\ciauth\index.php Line: 315
Function: require_once
Below is the controller
<?php
class Forms extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->library('session');
$this->load->helper('url');
$this->load->model('user_model', 'auth');
}
public function forgot_pass()
{
if($this->input->post('forgot_pass'))
{
$email=$this->input->post('email');
$this->load->model('user_model', 'auth');
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'E-mail', 'required');
if ($this->form_validation->run() == TRUE) {
$que=$this->db->query("select password,email from users where email='$email'");
$row=$que->row();
$user_email=$row->email;
if((!strcmp($email, $user_email)))
{
$pass=$row->password;
$to = $user_email;
$subject = "Password";
$txt = "Your password is $pass .";
$headers = "From: user#testdomain.com" . "\r\n" . "CC: hamza_zon#outlook.com ";
mail($to,$subject,$txt,$headers);
$this->load->view('user/header');
$this->load->view('user/confirm');
$this->load->view('user/footer');
}
else{
$data['error']="Invalid Email ID !";
}
}
else{
$data['error']="Email ID is required !";
}
}
$this->load->view('user/header');
$this->load->view('user/forgot_pass',#$data);
$this->load->view('user/footer');
}
}
?>

you should check before $user_email=$row->email; that the as per your criteria record exist or not, if row is not exist then you will get that error
so you should check as below
$row=$que->row();
if($row) {
$user_email=$row->email;
}

Try like this
$que = $this->db->query("select password,email from users where email=".$email);
if(isset($row) && $row != ''){
$txt = "Your password is" . $pass;
//Coding...
}

You need to handle it like this,
$query = $this->db->query("select password,email from users where email=".$email);
if ($query->num_rows() > 0) {
$row = $query->row();
$user_email = $row->email;
} else {
$user_email = '';
}
//then your next if condition in which you are comparing two strings

$row=$que->row();
$row is probably being returned as NULL or a falsy value.
var_dump($row) to check.
if(!$row)
{
die("user not found");
}
or
if(empty($row))
{
die("user not found");
}

Apply condition as, because in your case it may not getting the result from table for that email,
if (isset($row))
{
Note: row method returns a single result row. If your query has more than one row, it returns only the first row. The result is
returned as an object. Here’s a usage example:
$que=$this->db->query("select password,email from users where email like '$email'");
$row = $que->row();
if (isset($row))
{
$user_email = $row->email;
$user_password = $row->password;
}
Here is concise doc for the same.

Related

Why is the result of my code blank after executing query, on this line $out = $query->result_array();

this is the image of database table.
I'm new at codeigniter PHP
public function ForgotPassword($email)
{
$this->db->select('email');
$this->db->from('member');
$this->db->where('email', $email);
$query=$this->db->get();
$out = $query->result_array();
if (count($out) > 0) {
$email = $out[0]['email'];
return array('status'=>1, 'email'=>$email);
} else {
return array('status'=>0, 'msg'=>'email not found');
}
}
This is my model function., this line giving me blank result $out = $query->result_array(); I don't know why, it should give me email address so that i can proceed and send email. I want to send password to user using forgot password function.
public function ForgotPassword()
{
$email = $this->input->post('email');
$findemail = $this->MY_model->ForgotPassword($email);
if ($findemail['status'] == 1) {
$this->MY_model->sendpassword($findemail);
} else {
echo " $email not found, enter correct email id";
}
}
And this is my controller function. Here I'm getting blank value of $findemail. I don't know why.
public function sendpassword($data)
{
$email = $data['email'];
$query1=$this->db->query("SELECT * from member where email = '".$email."' ");
$row=$query1->result_array();
if ($query1->num_rows() > 0) {
$passwordplain = "";
$passwordplain = rand(10000000,99999999);
$newpass['password'] = md5($passwordplain);
$this->db->where('email', $email);
$this->db->update('member', $newpass);
$mail_message='Dear '.$row[0]['username'].','. "\r\n";
$mail_message.=' Your <b>Password</b> is
<b>'.$passwordplain.'</b>'."\r\n";
require 'C:\xampp\htdocs\phpmailer\class.phpmailer.php';
require 'class.phpmailer.php';
$mail = new PHPMailer;
$mail->IsSendmail();
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com";
$subject = 'Testing Email';
$mail->AddAddress($email);
$mail->IsMail();
$mail->From = 'vishal#gmail.com';
$mail->FromName = 'admin';
$mail->IsHTML(true);
$mail->Subject = $subject;
$mail->Body = $mail_message;
$mail->Send();
if (!$mail->send()) {
echo "Failed to send password";
} else {
echo "Password sent ! check your mail";
}
} else {
echo "Email not found!!!!";
}
}
And also upper model function , it's not sending email. I'm using phpmailer to sending email. Please help.
If your model name is 'MY_model' then write construct function in your controller file and load the model into it as shown below.
function __construct() {
parent::__construct();
$this->load->model('my_model');
}
And modify your ForgotPassword function of controller as below.
public function ForgotPassword()
{
$email = $this->input->post('email');
$findemail = $this->my_model->ForgotPassword($email);
if ($findemail['status'] == 1) {
$this->my_model->sendpassword($findemail);
} else {
echo " $email not found, enter correct email id";
}
}
I hope this helps.
I have made a function that checks if email exists in db. It is named CheckUser().
Then in ForgotPassword() you call CheckUser() ($email must be given as argument).
<?php
public function CheckUser($email)
{
$response = $bdd->prepare('SELECT email FROM member WHERE email = :email');
$response->execute([
"email" => $$email
]);
$data = $response->fetchAll();
return $data[0];
}
public function ForgotPassword($email)
{
// here you call our new function
** UDPATE BELOW CALLING OF CHECKUSER FUNCTION **
$out = $this->CheckUser($email);
// sizeof will return the lenght of the returned data from our CheckUser() function
if (sizeof($out) > 0){
$email = $out[0]['email'];
return array('status'=>1, 'email'=>$email);
}
else {
return array('status'=>0, 'msg'=>'email not found');
}
}
Let me know if it works.

Forgot password function not working in CodeIgniter

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 = '' . $url . '';
$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!
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
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
}
#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.

How to send email using template in Codeigniter

I want to send email using template. I have tried this code but it gives this error.
Severity: 4096
Message: Object of class CI_Loader could not be converted to string
My code is:
public function email_submit_change_password(){
$this->load->library('email');
$email = $this->input->post('email');
$check = $this->db->query("SELECT * FROM tbl_profile_main WHERE connect_to_email='".$email."';");
if($check->result()!=NULL){
$test = $this->load->view('includes/test');
$this->email->from('itsthunder07#gmail.com', 'Your Name');
$this->email->to($email);
$this->email->subject('Password Reset');
$this->email->message($test);
if($this->email->send()){
$this->db->query("UPDATE tbl_profile_main SET token_='".$token."' WHERE connect_to_email='".$email."';");
$this->session->set_userdata('email_send','success');
return 1;
// return 5;
}
}else{
$this->session->set_userdata('email_incorrect','error');
return 0;
}
}
If you want to return a view as a string, you have to load it as follows:
$test = $this->load->view('includes/test', '', true);
there should be check like this:
<?php
$check = $this->db->query("SELECT * FROM tbl_profile_main WHERE connect_to_email='".$email."';");
if($check->num_rows() > 0) { // check data exists or not
$r = $check->result_array();
if(!empty($r)) {
// send email process
} else {
$this->session->set_userdata('email_incorrect','error');
return 0;
}
}
?>

Codeigniter Login

Ive got a Codeigniter login system here, and just wondering where im going wrong. Heres my code:
View
<?php
echo form_open('handyman/logIn');
echo form_label('Email: ','useremail');
echo form_input('useremail');
echo "<br />";
echo form_label('Password: ','userpassword');
echo form_input('userpassword');
echo "<br />";
echo form_submit('Logmein','Log In');
echo form_close();
?>
Controller
public function logIn(){
$useremail=$this->input->post('useremail');
$userpassword=md5($this->input->post('userpassword'));
$this->load->model("HandymanModel");
if($useremail && $userpassword && $this->HandymanModel->logInUser($useremail,$userpassword)){
$data['msg']="Successfully Logged in!";
$data['title']="Logged In";
$this->load->view("header",$data);
$this->load->view("confirmation",$data);
$this->load->view("footer",$data);
} else{
$data['title']="Sign up / Log in";
$this->load->view("header",$data);
$this->load->view("page3", $data);
$this->load->view("footer",$data);
}
}
Model
function logInUser($useremail,$userpassword) {
$this->db->where('email',$useremail );
$this->db->where( 'password', $userpassword );
$login = $this->db->get()->result();
if (is_array($login) && count($login) == 1) {
return true;
} else {
return false;
}
I'm getting Error Number: 1064 which is check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE email = 'email#gmail.com' AND password = '1a1dc91c9073' at line 2
Thanks
You re missing the table name
$login = $this->db->get( )->result();
^^here
Try this by adding table name
$login = $this->db->get('your table name')->result();
$this->db->get();
I would change your model to something like...
function logInUser($useremail,$userpassword) {
$query = $this->db->query('SELECT * FROM tbl_name WHERE account_email="'.$useremail.'" AND account_password = "'.$userpassword.'"');
if ($query->num_rows() != 0){
return true;
} else {
return false;
}
}
I would also suggest encrypting user passwords as well. take a look at MD5. Make sure you use a hash as well.
Cheers!

Variable returning as undefined in codeigniter?

I am getting the following error message for each variable:
Message: Undefined index: on lines 59, 60, 61, 62
I cannot understand why as it is definitely getting the sessions data and also the databases are setup and their is a user which matches that criteria.
jobs.php(apply function):
public function apply(){
if($this->session->userdata('is_logged_in')){
$this->load->view('header');
$this->load->view('job');
$id = $this->session->userdata('id');
$query = $this->db->get_where('jobseeker_profiles', array('jobseeker_id' => $id));
$user = $query->row_array();
$points = $user['total_points_value'];
$name = $user['name'];
$email = $user['email'];
$jobseeker_profile_id = $user['id'];
$employer_profile_id = $this->input->post('employer_id');
$job_id = $this->input->post('job_id');
$this->db->set('jobseeker_profile_id', $jobseeker_profile_id);
$this->db->set('employer_profile_id', $employer_profile_id);
$this->db->set('job_id', $job_id);
$this->db->set('name', $name);
$this->db->set('email', $email);
$this->db->set('points_value', $points);
if($this->input->post('submit')){
$this->db->insert('applications');
}
redirect('applied-for');
}else{
redirect('login');
}
}
}
Hope fully you can help, thanks!
Have you checked if the 4 database variables you are setting in those lines are rightly declared in the table ? They have to match to work.
do some quick error checking directly from the controller or model like
// check if query did not come back
if ( ! $query = $this->db->get_where('jobseeker_profiles',array('jobseeker_id' => $id)) )
{ echo 'OMFG WHERE IS MY QUERY ???' ; }
else
{ $user = $query->row_array();
echo 'QUERY WORKED, User Name is:' . $user['name'] ;
}
and if this does not work, go back and make sure you are loading the database, that the user/password is correct, etc

Categories