Codeigniter Trying to get property of non object - php

I have developed a web application using Codeigniter. It all works perfectly on localHost, but now that I uploaded it to a server I have one single issue. Everything works as it's supposed to except my redirect when the user inserts the wrong password. It was supposed to redirect back to login page and display an error message (which works with localhost ), but I get the following errors.
I decided to not redirect and simply load my login view again, it worked, but I still get the Trying to get property of non object error message, which is weird cause I didn't get this error working on localhost.
My controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function index()
{
$this->load->view('header');
$this->load->view('login_view');
$this->load->view('footer');
}
public function to_login() {
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if($this->form_validation->run() == FALSE) {
$data = array(
'errors' => validation_errors()
);
$this->session->set_flashdata($data);
redirect('index.php/Login');
} else {
$email = $this->input->post('email');
$password = $this->input->post('password');
// the following lines are 38 and 39
$user_id = $this->Login_model->login_user($email, $password)->user_id;
$first_name = $this->Login_model->login_user($email, $password)->first_name;
if($user_id) {
$user_data = array(
'user_id' => $user_id,
'first_name' => $first_name,
'logged_in' => true
);
$this->session->set_userdata($user_data);
redirect('http://gc200322197.computerstudi.es/app/index.php/Main');
} else {
$this->session->set_flashdata('login_fail', 'Invalid login. Please check the email and password fields.');
$this->load->view('header');
$this->load->view('login_view');
$this->load->view('footer');
}
}
}
My model:
<?php
class Login_model extends CI_Model{
public function login_user($email, $password) {
$this->db->where('email', $email);
$result = $this->db->get('users');
$db_password = $result->row(4)->password;
if(password_verify($password, $db_password)) {
return $result->row(0);
} else {
return false;
}
}
}
I've read so many questions about this error and I still couldn't figure out what is wrong and why it works on localhost and not online. I'd really appreciate some help on this.

Focusing on line #38, your model is returning one of two datatypes and your controller code is not accommodating it:
$user_id = $this->Login_model->login_user($email, $password)->user_id;
should be changed into:
$user_id = $this->Login_model->login_user($email, $password); // This could be false or an object
// Check if we've received an object
if($user_id){
$user_id = $user_id->user_id; // Access the object's property
$first_name = $user_id->first_name; // Might as well set the first name as well
}
A better option would be renaming some variables like this:
$user_info = $this->Login_model->login_user($email, $password); // This could be false or an object
// Check if we've received an object
if($user_info){
$user_id = $user_info->user_id; // Access the object's property
$first_name = $user_info->first_name; // Might as well set the first name as well
}
Update:
For anyone confused about CodeIgniter models, speaking to v3.0.4, see below:
Example 1
$this->load->model('Login_model');
$this->Login_model->some_func(); // Works
$this->login_model->some_func(); // Fails
Example 2
$this->load->model('login_model');
$this->Login_model->some_func(); // Fails
$this->login_model->some_func(); // Works
It is only a recommendation that you should declare and access models with lowercase, example #2; it will make your life easier.
Based on OPs code and comments, it appears that they have loaded the model using example #1 so merely suggesting to use $this->login_model would break the code further.

Related

Codeigniter - Controller can't render view

I' facing a problem with trying to render login_view.php in my login.php controller. What I got is this error :
Firefox has detected that the server is redirecting the request for
this address in a way that will never complete.
This problem can sometimes be caused by disabling or refusing to accept cookies.
Here is my controller
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form','url','html'));
$this->load->library(array('session','form_validation'));
$this->load->database();
$this->load->model('user_model');
}
function index()
{
//get form input
$email = $this->input->post('email');
$password = $this->input->post('password');
//form validation
$this->form_validation->set_rules('email','Email-ID','trim|required|xss_clean');
$this->form_validation->set_rules('password','Password','trim|required|xss_clean');
if($this->form_validation->run() == FLASE)
{
//validation fail
$this->load->view('login_view');
}
else
{
//check user credentials
$uresult = $this->user_model->get_user($email, $password);
if(count($uresult)>0)
{
//set session
$sess_data = array('login' => TRUE, 'uname' => $uresult[0]->fname,'uid' => $uresult[0]->id);
$this->session->set_userdata($sess_data);
redirect('profile/index');
}
else
{
$this->session->set_flashdata('msg','<div class = "alert alert-danger text-center">Wrong Email/Password</div>');
redirect('login/index');
}
}
}
}
Please help me figure out whats the problem. Thank you.
I suggest you to load session library in autoload, since you will need it on other pages. Beside, you have a typo in the first if condition.
if($this->form_validation->run() == FLASE) // FIX FALSE
Fixed it! turns out I've mistaken using redirect instead of $this->load->view('login_view'); and $this->load->view('profile_view');
It seems if I use redirect and the code will always check if the if(count($uresult)>0) is TRUE or FALSE and then continue with the action, The redirect action will always runs. So it's endless loop.
Check out the check user credentials conditional statement.

Sometimes Trying to get property of non-object

After login after some random time when i refresh any page on website, sometimes it works perfectly, but sometimes it shows error like Trying to get propert on different lines of model and controller file.
For example, when i refresh the page error was shown in below function of model named user_model and controller named User.php:
User_model.php:
public function get_client_id($email)
{
$this->db->select('id');
$this->db->where('email', $email);
$query = $this->db->get('crm_accounts');
$result = $query->row();
return $result->id; //line 135
}
Users.php:
$email = $_SESSION['email'];
$id = $this->user_model->get_client_id($email); //line 145
Setting the session value after login:
$email = $this->input->post("email");
$password = $this->input->post("pass");
$result = $this->user_model->login($email, $password);
if ($result == TRUE)
{
$this->session->set_userdata('email',$email);
$this->session->set_userdata('logged_in',TRUE);
$data = $this->user_model->get_username($email);
$this->session->set_userdata('data', $data);
redirect('admin_view');
}
else
{
$this->load->view('all_field');
}
code for deleting the session after logout:
$logged_in = $this->session->userdata('logged_in');
$log = $this->session->userdata('email');
if($logged_in || (!empty($log)))
{
$array_item = array('email', 'logged_in');
$this->session->unset_userdata($array_item);
redirect('');
}
else
{
$this->load->view('error_page');
}
Here, i got error on like
Tring to get property of non-object on line 135 of user_model.php and in backtrace it found error on Users.php on line 145
I have noticed that when i get this type of error in model, i am getting data in that particular method using session variable $email in which the session data is stored. But i have put such condition in controller:
public function index()
{
if(!empty($_SESSION['email']))
{
$email = $_SESSION['email'];
$data = $this->user_model->get_username($email);
$this->session->set_userdata('data',$data);
redirect('clientview');
//echo "You are already logged in";
}
else
{
$this->load->view('signup');
}
}
So, if the value of session variable $email is not set than it should go on signup page.
So, i am not getting what is actually problem. Because sometimes it works perfectly and sometimes not. Once if i get such error, i have to clear my history and than i have to log in again.
In Codeigniter you have a specific way to get form or set values in the session.
If you want to check if the session exist you need to do
$this->session->userdata('email');
Which will retrieve the stored value.
And as you already do:
$this->session->set_userdata('email', $email);
To set a value in the session.
Additionally when the user is logging out yoi need to reset the stored value, ptherwise it will never be empty.
$this->session->set_userdata('email', '');
NOTE: What you are doing is of course not the best way to do such kind of stuff, as a login and logout system. I suppose you are just learning and you are doing this not for a production application.
If you do, please try to use ionAuth authentication library for Codeigniter, that you can find here:
http://benedmunds.com/ion_auth/
And follow some tutorial about it:
http://www.tutorials.kode-blog.com/codeigniter-authentication
Just keep in mind that user authentication is a serious security matter so be carefull.

Session in Code Igniter

I want to ask this question if how can we make a session in code igniter specially in logging in and logging out on the account. I want to know the step by step following the MVC of code igniter.
At the login time after executing query set session data in set_userdata function and passing data array whos you want to set.
$this->session->set_userdata('session data here');
And at the time of logout you have to call unset_userdata function and passing array of array whos you have to set at login time.
$this->session->unset_userdata('session data here');
using my code as an example you can do this i have a controller called iris.php and a model called script.php. i use the iris to call and make use of the script model.
class Iris extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('script');
$this->load->model('alert');
}
public function index()
{ $this->load->view('index');
}
public function login_in()
{
$login = $this->script->check_login();
if($login->num_rows() == 1){
foreach ($login->result_array() as $row) {
$newdata = array(
'fullname' => $row['fullname'],
'email' => $row['email'],
'member_id' => $row['member_id'],
'transtatus'=>$row['transtatus']
);
$this->session->set_userdata($newdata);
}
redirect('iris/user_home');
}else
{
$data = array('alert'=>$this->alert->log_alert());
$this->load->view('common/header');
$this->load->view('login',$data);
$this->load->view('common/footer');
}
}`
i first load the model script model under the constructor and in the login function of the iris controller i called the function in the script $login=$this->script->check_login();
in the script.php we have the following code.
{public function check_login(){
$email = $this->input->post('email');
$password = $this->input->post('password');
$query = "SELECT * FROM `iris_user`
WHERE`email`=? AND`password`= ? ";
$result = $this->db->query($query, array($email, $password));
return $result;
}
remember you have to have loader the session class helper form the application/config/autoload.php file in the CIfolder
$autoload['libraries'] = array('database', 'session');
the session is alway start once it has been autoloaded, but can be destroyed when maybe creating a logout function.
also note when adding to the session data variable to access the session variable you will have to use the name that was used when declaring the session variable. e.g to access the fullname you would do this in code
echo $_SESSION['fullname'];
In the controller load library session :
$this->load->library('session');
Use below sentence for session create :
$this->session->set_userdata("session_name",session_value);
For Session Unset:
$this->session->unset_userdata("session_name");

codeigniter session lost when refresh (F5)

First of all i'm new for codeigniter. All i want to ask is, why every refresh my session data is lost. i redirect to login.
Here is my code.
login controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
$this->load->helper('form');
$this->load->view('login');
}
}
?>
verifylogin
function index() {
//This method will have the credentials validation
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', '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->load->view('headerx');
//redirect('login', 'refresh');
$this->load->view('login');
}
else {
//Go to private area
redirect('home');
}
}
function check_database($password) {
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//query the database
$result = $this->user->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', 'Invalid username or password');
return false;
}
}
?>
home controller
function index()
{
if($this->session->userdata('logged_in')) {
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$this->load->view('home', $data);
}
else {
//If no session, redirect to login page
// print_r($this->session->all_userdata());
//die();
redirect('login');
}
}
first login it is success, but when i refresh (f5) it is back to login form.
my opinion its because session is lost.
thanks for any help...
EDIT AND SOLVED :
sorry for inconvenience, this problem happen because
<script>
function goOut(){
<?php $this->session->unset_userdata('logged_in');?>
window.location="<?php echo base_url()?>";
}
</script>
my purpose it is when click button logout, then session is unset, but if i input in the header, session will be lost again, so i will find another way. thank you for your attentions and help.
I would try using CodeIgniter's sessions in the database instead. I've had problems with CI in the past with this sort of problem. It usually occurs when you're setting a large amount of data (greater than 4KB) in the cookie.
Let me know if database-based sessions is not an option.
See here for more information: CodeIgniter Sessions See heading "Saving Session Data to a Database"
If you are on windows there is an issue with Codeigniter, PHP 7, and Apache on Windows 10. I had a client who wanted the staging application on their own laptop, and this only happened on their new laptop.
So after hours of testing, we uninstalled XAMPP 7.1.4, and reinstalled XAMPP with version 5.6.XX. And that fixed it. Yet, there were no issues on Linux boxes running Nginx and PHP 7. Just Windows 10.
Anyway, I hope this helps! It took me hours to find the solution.

codeigniter redirect fails only when i include "refresh"

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class VerifyLogin extends CI_Controller
{
public function __construct()
{
parent::__construct();
//Model for fetching users in database
$this->load->model('user', '', TRUE);
}
public function index()
{
//Load method to help verify form credentials
$this->load->library('form_validation');
//-----------------------------------------------
//Verify Existance of values in login form fields
//-----------------------------------------------
//Validate existance of username field value
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
//Validate existance of password field value, and if exists then call 'check_database' func
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
//If the form validation is false (i.e. Missing form fields)
if($this->form_validation->run() == FALSE){
//Redirect back to login page
$this->load->view('general-Login');
}
//Login Success, goto main-page
else{
//Go to main page
redirect('Main', 'refresh');
}
}
function check_database($password)
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//Check the username and password against database
$result = $this->user->login($username, $password);
//If there is a result
if($result){
//will be used for session information
$sess_array = array();
foreach ($result as $row){
$sess_array= array(
'id' => $row->id,
'username' => $row->username
);
//Session set as logged in
$this->session->set_userdata('logged_in', $sess_array);
}
return true;
}
//No existance of user or, incorrect password
else{
//Send Message of incorrect username or password
$this->form_validation->set_message('check_database', 'Invalid Username or Password');
return false;
}
}
}
So i have a verifylogin controller that handles the form data from my login page. Database access works great and everything works perfectly until i get to the redirect feature. I try to redirect with refresh and it just gives me a page that says "undefined". Now it will suddenly work when i remove the 'refresh' and just leave the controller name, but i'm trying to figure out why this 'refresh' won't work.
I've disabled my .htaccess
I've tried setting my $config['uri_protocol'] to REQUEST_URI, AUTO, and PATH_INFO
and had no luck.
Also, this is my first submission online to anything like a forum so please....be gentle.
First off, welcome to Stack Overflow.
Secondly, if redirect() without the "refresh" works, I would run with it and figure it out later.
For a deeper explanation, "refresh" attempts to do a meta-like refresh to the page similar to:
<meta http-equiv="refresh" content="0;URL='http://example.com/'">
(Note: It doesn't do that within your view, but rather sends the browser a similar snippet in the response)
What browser are you using? What version? Hopefully it's something up-to-date, because that could make a difference in how the refresh works.
I had similar problem. E.g. on my localhost refresh do not work and on the hosting provider settings it works. Maybe something in Apache/PHP configuration. Go without refresh, it is OK. I do not think it has something to do with a browser. I was using the same browser when that happened.

Categories