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.
Related
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.
I'm trying to learn MVC pattern but,even if I'm trying hard, it seems I still got big issues.
I have got a controller,named baseController that do the following:
class baseController {
public $model;
public $user;
...
$activeuser = $this->model->getlogin();
if ($activeuser != 'invalid user' && $activeuser != "") {
$this->user=$activeuser;
header("Location:home.php");
}
I have got a model.php file which contains the getlogin() function:
public function getlogin() {
if (isset($_REQUEST['username']) && isset($_REQUEST['password'])) {
$username = mysql_real_escape_string($_REQUEST['username']);
$pwd = mysql_real_escape_string($_REQUEST['password']);
$pwd = md5($pwd);
$query = mysql_query("SELECT * FROM users WHERE username='$username' AND password ='$pwd' AND attivato =1;");
if (mysql_num_rows($query) == 1) {
require_once 'User.php';
$sql=mysql_fetch_array($query);
$activeuser = new User();
$activeuser->username=$sql['username'];
$activeuser->email=$sql['email'];
return $activeuser;
} else {
return 'invalid user'; //TO-DO
}
}
}
The home.php create a new homeController and calls its invoke() function.The homeController file include the view page,that's called afterlogin.php.
In the afterlogin.php I've got the "ERROR":
if (isset($activeuser)){
echo "<p>Utente ".$activeuser->username."</p>";
echo "<p>Email ".$activeuser->email."</p>";}
//echo "<p>Pass ".$activeuser->pwd."</p>";
echo"<h1> HOMEPAGE, LOGIN OK </h1>";
It seems the homeController,and so the afterlogin page cannot access the user created in the baseController file. If I try an echo inside the baseController of $this->user->username everything is working. What should I do?? HELP!!
The client-server lifecycle is effectively stateless; on every page load, your variables and objects are wiped out.
There are the client-sourced $_POST and $_GET superglobals, which is part of the standard form submission and url query processes.
The server has databases, file writing (sketchy from a security POV) and the $_SESSION superglobal. These are the ways the server can manage a data state between pageloads.
Understand that if you're using objects, you need to have them instantiated on every page load for them to work. You can store your user_ID in $_SESSION['user_ID'] and instantiate the user object from it every time, making appropriate changes according to how the data changes.
I am trying to make a login validation page for my class and this is the code I have for the page LoginDataModel.php.
<?php
//define a constant variable for fxUsers.ini
define('FX_LOGIN_INI_FILE', 'fxUsers.ini');
class LoginDataModel {
private $ini_array;
//construct class will read and store an associative array
public function __construct() {
$this->ini_array = parse_ini_file(FX_LOGIN_INI_FILE);
}
//validateUser function will compare the username and password
//given by the user to the values stured in the ini file.
public function validateUser($username, $password){
if(in_array($username,$this->ini_array) && in_array($password,$this->ini_array)){
return TRUE;
} else {
return FALSE;
}
}
}
?>
This code will be called in my login.php page once the user passes through his credentials. If the users credentials do not match, he will simply be rerouted back to the login page to try again. The code for the login page is
<?PHP
//check for key to see if this is the first time loading the page
if (empty($_POST['txtUser'])){
$user = '';
$pass = '';
} else {
$user = $_POST['txtUser'];
$pass = $_POST['txtPassword'];
}
//call method from a different file
require_once ('LoginDataModel.php');
$LoginDataModel = new LoginDataModel();
$control = $LoginDataModel->validateUser($user, $pass);
//if user and password match, continue to next file and exit current file
if($control === TRUE){
include 'fxCalc.php';
exit();
}
?>
While I believe to have everything set, The only thing I need is how to compare the values between the user and the values in the ini file. Any help would be appreciated
EDIT
I should have mentione that my ini file will just be
[section]
admin = pass
EDIT 2
My code reflect the changes I've made thanks to the support from this post as well as looking back at my text book. My problem is now that When I pass the user and pass through the file, it returns as false even though the strings match perfectly.
You are doing the wrong way of comparison in the below line..
if($ini_array == $username && $ini_Array == $password){
The parse_ini_file() returns an array , so you just can't check a variable $username inside an array (i.e. $ini_array) using a == operator. You should be using array_search or in_array() functions as such.
Something like...
if(in_array($username,$ini_array) && in_array($password,$ini_Array)){
I have an installation of Codeigniter, IonAuth + Hybridauth which I am reworking so my users can choose their own username instead of generating one using the first and last names returned by facebook.
So in my code below I check to see if a username was posted, if not I want to load the choose_username view but for some reason the view is not loading and its completely skipping that section which is why I added die('Why no view')
Update: This first piece of code runs fine in a new controller
Checkout the code here:
if(isset($_POST['username'])){
$username = $this->input->post('username', TRUE);
die($username);
}else{
$this->data['message'] = 'Please choose a username.';
$this->data['template'] = 'guests/partials/choose_username';
$this->load->view('guests/template/standard', $this->data);
die('Why no view?');
};
Longer version:
function login_provider($provider = '')
{
if(empty($provider)) redirect();
try
{
// create an instance for Hybridauth with the configuration file
$this->load->library('HybridAuthLib');
if ($this->hybridauthlib->serviceEnabled($provider))
{
// try to authenticate the selected $provider
$service = $this->hybridauthlib->authenticate($provider);
if ($service->isUserConnected())
{
// grab the user profile
$user_profile = $service->getUserProfile();
////////////
//var_dump($user_profile);
//die();
////////////
$provider_uid = $user_profile->identifier;
if($this->ion_auth->login_by_provider($provider,$provider_uid))
{
$data['user_profile'] = $this->ion_auth->user_by_provider();
//$this->load->view('auth/user_profile',$data);
$user = $this->ion_auth->user()->row();
//Redirect to custom subdomain
$url = explode('://',site_url());
if (strpos(site_url(),$user->username) !== false) {
redirect($url[0].'://'.str_replace('www','',$url[1]).'dashboard','refresh');
}
else{
redirect($url[0].'://'.$user->username.str_replace('www','',$url[1]).'dashboard');
};
}
else
{ // if authentication does not exist and email is not in use, then we create a new user
//Check if username was posted
if(isset($_POST['username'])){
$username = $this->input->post('username', TRUE);
die($username);
}else{
$this->data['message'] = 'Please choose a username.';
$this->data['template'] = 'guests/partials/choose_username';
$this->load->view('guests/template/standard', $this->data);
die('Why no view?');
};
So when I run the above code, all i get is a blank page with: Why no view.
As above, usually when I run into this sort of issue it's from a bug in the view code.
Also, I don't know what, is actually being passed by this post in the event of there not being username data but you might want to also be checking for an empty value for username. This is probably not the issue but it would be good to confirm that the initial if is evaluating the way you expect.
I am building a social network via code igniter. Upon registration, the potential member get's stored in the db, and their status get's marked to pending. I then send them a confirmation email with a hashed token link. When they hit the link it marks their account as active and takes them to a welcome page that has a sign in.
When I go to the link it sets of an infinite loop and freezes my computer when I'm working on my MAMP. ( or I'm suspicious that it's an infinite loop )
Here is my pertinent code:
auth CONTROLLER that sends the email:
function varification_email()
{
$query = $this->db->query('SELECT * FROM users order by id desc LIMIT 1');
$token = sha1($user->email.$user->salt).dechex($user->id);
$domain = "clci.dev/index.php";
$link = "http://www.".$domain."/account/confirmation/?token=$token";
foreach ($query->result() as $user)
{
$this->load->library('email');
$this->email->from('noreply#cysticlife.org', 'CysticLife');
$this->email->to($user->email);
$this->email->subject('Welcome to CysticLife!');
$this->email->message("Thanks for signing up for CysticLife! To complete the registration process please go to the following web address:\n\n$link\n\n-Your friends at CysticLife\n\nPlease remember to add the cysticlife.org domain to your address book to ensure that you receive your CysticLife e-Notifications as requested.eh");
$this->email->send();
}
account CONTROLLER that the user is linked back to from the email:
public function confirmation() {
$data['main_content'] = 'account/confirmation';
$this->load->view('includes/templates/main_page_template', $data);
$this->load->library('encrypt');
$this->load->helper('url');
$this->load->library('session');
$this->load->model('user_model', 'um');
$login = $this->input->post('submit');
//IF THE SUBMIT BUTTON IS TRIGGERED THE POST DATA IS SENT TO THE VALIDATE FUNCTION IN THE MODEL VIA VARIABLES CREATED
if($login) {
$user = $this->um->validate(array('email' => $this->input->post('email')));
if( $user ) {
// CHECK THE USER'S PASSWORD AGAINST THE ONE FROM THE LOGIN FORM
if($user->password == $this->encrypt->sha1( $user->salt . $this->encrypt->sha1($this->input->post('password')))) {
$this->session->set_userdata('logged_in', TRUE);
$this->session->set_userdata(array(
'email' => $this->input->post('email')
));
$this->session->userdata('logged_in');
redirect('account/dashboard');
exit;
}
}
}
$this->index();
}
Thanks in advance
varification_email()
In varification_email(), $user is used before it is defined. I assume the real code doesn't have this issue.
Your method for selecting the user in the DB in prone to concurrency errors (wrong user returned).
confirmation()
I already had encountered browser hangs because of too large cookies, exceeding something like 4 kB. Have a look at that.
The problem might be in user_model->validate(). Comment out the following of the code and check if it works.