Fatal error: Call to a member function getUserID() - php

I am getting the following error when I check my site:
Fatal error: Call to a member function getUserID() on a non-object in /home/clientwo/public_html/main/registry/authenticate.php on line 104
This is the code:
<?php
class Authenticate {
private $user;
private $status;
private $loggedIn = false;
public function __construct(Registry $registry) {
$this->registry = $registry;
$this->status = 'User is logged out';
}
private function checkForAuthentication() {
if (isset($_SESSION['sn_auth_session_uid']) && $_SESSION['sn_auth_session_uid'] > 0) {
$this->sessionAuthenticate(intval($_SESSION['sn_auth_session_uid']));
}
}
private function sessionAuthenticate($id) {
//build a user model
require_once FRAMEWORK_PATH . 'model/user.php';
$this->user = new UserModel($this->registry, $id);
//check if user is valid etc
if ($this->user->isValid()) {
if (!$this->user->isActive()) {
$this->loggedIn = false;
$this->status = 'User has been deleted';
} else {
$this->loggedIn = true;
$this->status = 'User is logged in';
}
} else {
$this->loggedIn = false;
$this->status = 'User could not be found';
}
//make sure sessions are not set if user is not logged in
if (!$this->loggedIn) {
$this->logout();
}
}
public function login($username, $password) {
//first log out
$this->logout();
//execute query
$this->registry->getObject('mysql')->executeQuery("SELECT UserID FROM user WHERE Username='". $username . "' AND password='" . md5($password) . "'");
//check if query returned one row
if ($this->registry->getObject('mysql')->numRows() == 1) {
//get user row
$UserData = $this->registry->getObject('mysql')->getRow();
//build a user model
require_once FRAMEWORK_PATH . 'model/user.php';
$this->user = new UserModel($this->registry, $UserData['UserID']);
//check if user is valid and active etc
if ($this->user->isValid()) {
if ($this->user->isActive() == false) {
$this->loggedIn = false;
$this->status = 'User has been deleted';
} else {
$this->loggedIn = true;
$this->status = 'User is logged in';
$this->user->increaseLogins();
$this->user->update();
$_SESSION['sn_auth_session_uid'] = $this->user->getUserID();
}
} else {
$this->loggedIn = false;
$this->status = 'Authentication failed';
}
} else {
$this->loggedIn = false;
$this->status = 'Authentication failed';
}
}
function logout() {
//if such a session is set, unset it
if (isset($_SESSION['sn_auth_session_uid'])) {
unset($_SESSION['sn_auth_session_uid']);
}
//reset to logged out
$this->loggedIn = false;
//reset to null
$this->user = null;
}
public function isLoggedIn() {
$this->checkForAuthentication();
return $this->loggedIn;
}
public function isAdmin() {
$this->checkForAuthentication();
return $this->user->isAdmin();
}
public function getUser() {
$this->checkForAuthentication();
return $this->user;
}
public function getUserID() {
$this->checkForAuthentication();
return $this->user->getUserID();
}
public function getStatus() {
$this->checkForAuthentication();
return $this->status;
}
}
?>

This line is not returning the user object
$this->user = new UserModel($this->registry, $UserData['UserID']);

Related

Login Attempts - Codeigniter - Not Working

I want to workout a function such that unsuccessful login attempts of user are capped at 3 consecutive failed login attempts, then serve them a message to that effect. It is immediately executing this line:
if ($isBlocked) {
$this->form_validation->set_message('check_user', 'Account is temporarily blocked.');
}
Somethings wrong on my code. Thanks in advance for the help.
Controller
<?php
class Account_login extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$data['title'] = 'Account Login';
$this->load->view('account_login', $data);
}
public function verify()
{
$this->form_validation->set_rules('acc_username', 'Username', 'required');
$this->form_validation->set_rules('acc_password', 'Password', 'required|callback_check_user');
if ($this->form_validation->run() === TRUE) {
echo 'Success';
} else {
$this->index();
}
}
public function check_user()
{
$username = $this->input->post('acc_username');
$password = $this->input->post('acc_password');
$this->load->model('account_login_model');
$login = $this->account_login_model->login($username, $password);
if ($login) {
return true;
} else {
if (isset($_SESSION['error_count'][$username])) {
$_SESSION['error_count'][$username] += 1;
} else {
$_SESSION['error_count'][$username] = 1;
}
$isBlocked = $this->account_login_model->isBlocked($username);
if ($isBlocked) {
$this->form_validation->set_message('check_user', 'Account is temporarily blocked.');
} else if (isset($_SESSION['error_count'][$username]) && $_SESSION['error_count'][$username] > 2) {
$this->account_login_model->block($username);
$this->form_validation->set_message('check_user', '3 consecutive failed login attempts. Account Blocked.');
} else {
$this->form_validation->set_message('check_user', 'Invalid Username/Password');
}
return false;
}
}
}
Model
<?php
class account_login_model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function login($username, $password)
{
$condition_array = array(
'acc_username' => $username,
'acc_password' => $password
);
$rs = $this->db->get_where('accounts', $condition_array);
return $rs->row_array() ?: false;
}
public function isBlocked($username)
{
$condition_array = array(
'acc_username' => $username,
'acc_isBlocked' => 1
);
$rs = $this->db->get_where('accounts', $condition_array);
$row_count = count($condition_array);
if ($row_count > 0) {
return true;
} else {
return FALSE;
}
}
public function block($username)
{
$this->load->library('email');
$email = $this->account_lookup($username, 'acc_email');
$this->email->from('<email>', 'Yahoo.com');
$this->email->to($email);
$this->email->subject('Account Blocked');
$message = $this->load->view('account_blocked', null, TRUE);
$this->email->message($message);
$this->email->send();
$this->db->where('acc_username', $username);
return $this->db->update('accounts', array('acc_isBlocked' => 1));
}
public function account_lookup($username, $return)
{
$rs = $this->db->get_where('account', array('acc_username' => $username));
$row = $rs->row();
return $row->$return;
}
}

How to display a logged in user name in my oop php project?

When I try to display a username from my logged in user in my project, I get this error Undefined variable: user_id in C:\xampp\htdocs\login1\index.php on line 2
Query Failed!!!You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1 . Here is my code:
index.php:
<?php require_once("includes/header.php"); ?>
<?php $user = User::find_user_by_id($user_id); ?>
<?php
if (!$session->is_signed_in()) {
redirect("login.php");
}
?>
<div class="row">
<div class="col-md-12">
<h1>Home</h1>
<h1>Hello, <?php echo $user->username; ?></h1>
</div>
<?php require_once("includes/footer.php"); ?>
user.php:
class User
{
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
private function has_the_attribute($the_attribute)
{
$object_properties = get_object_vars($this);
return array_key_exists($the_attribute, $object_properties);
}
public static function instantation($the_record)
{
$the_object = new self;
foreach ($the_record as $the_attribute => $value) {
if ($the_object->has_the_attribute($the_attribute)) {
$the_object->$the_attribute = $value;
}
}
return $the_object;
}
public static function find_this_query($sql)
{
global $database;
$result_set = $database->query($sql);
$the_object_array = [];
while ($row = mysqli_fetch_array($result_set)) {
$the_object_array[] = self::instantation($row);
}
return $the_object_array;
}
public static function find_all_users()
{
return self::find_this_query("SELECT * FROM users");
}
public static function find_user_by_id($user_id)
{
global $database;
$the_result_array = self::find_this_query("SELECT * FROM users WHERE id=$user_id");
return !empty($the_result_array) ? array_shift($the_result_array) : false;
}
public static function verify_user($username, $password)
{
global $database;
$username = $database->escape_string($username);
$password = $database->escape_string($password);
$sql = "SELECT * FROM users WHERE ";
$sql .= "username = '{$username}' ";
$sql .= "AND password = '{$password}'";
$the_result_array = self::find_this_query($sql);
return !empty($the_result_array) ? array_shift($the_result_array) : false;
}
}
$user = new User();
session.php:
<?php
class Session
{
private $signed_in = false;
public $user_id;
public $message;
public function __construct()
{
session_start();
$this->check_the_login();
$this->check_message();
}
public function login($user)
{
if ($user) {
$this->user_id = $_SESSION['user_id'] = $user->id;
$this->signed_in = true;
}
}
public function logout()
{
unset($_SESSION['user_id']);
unset($this->user_id);
$this->signed_in = false;
}
private function check_the_login()
{
if (isset($_SESSION['user_id'])) {
$this->user_id = $_SESSION['user_id'];
$this->signed_in = true;
} else {
unset($this->user_id);
$this->signed_in = false;
}
}
public function is_signed_in()
{
return $this->signed_in;
}
public function message($msg="")
{
if (!empty($msg)) {
$_SESSION['message'] = $msg;
} else {
return $this->message;
}
}
public function check_message()
{
if (isset($_SESSION['message'])) {
$this->message = $_SESSION['message'];
unset($_SESSION['message']);
} else {
$this->message = "";
}
}
}
$session = new Session();

How to dynamically display user name from the database after log in?

I need to dynamically display user name from logged in user in my OOP PHP project. I can display it when I type right id from the database but it shows error when I try to define property $user_id in my function find_by_id. I need help on how to define $user_id variable. Here is my code:
index.php
<?php $user = User::find_by_id($user_id); ?>
<h1>Hello, <?php echo $user->username; ?></h1>
user.php
<?php
class User
{
protected static $db_table = "users";
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
private function has_the_attribute($the_attribute)
{
$object_properties = get_object_vars($this);
return array_key_exists($the_attribute, $object_properties);
}
public static function instantation($the_record)
{
$the_object = new self;
foreach ($the_record as $the_attribute => $value) {
if ($the_object->has_the_attribute($the_attribute)) {
$the_object->$the_attribute = $value;
}
}
return $the_object;
}
public static function find_this_query($sql)
{
global $database;
$result_set = $database->query($sql);
$the_object_array = [];
while ($row = mysqli_fetch_array($result_set)) {
$the_object_array[] = self::instantation($row);
}
return $the_object_array;
}
public static function find_all()
{
return self::find_this_query("SELECT * FROM " . static::$db_table . " ");
}
public static function find_by_id($user_id)
{
global $database;
$the_result_array = self::find_this_query("SELECT * FROM " . self::$db_table . " WHERE id = $user_id");
return !empty($the_result_array) ? array_shift($the_result_array) : false;
}
public static function verify_user($username, $password)
{
global $database;
$username = $database->escape_string($username);
$password = $database->escape_string($password);
$sql = "SELECT * FROM " . self::$db_table . " WHERE ";
$sql .= "username = '{$username}' ";
$sql .= "AND password = '{$password}'";
$the_result_array = self::find_this_query($sql);
return !empty($the_result_array) ? array_shift($the_result_array) : false;
}
}
$user = new User();
session.php
<?php
class Session
{
private $signed_in = false;
public $user_id;
public $message;
public function __construct()
{
session_start();
$this->check_the_login();
$this->check_message();
}
public function login($user)
{
if ($user) {
$this->user_id = $_SESSION['user_id'] = $user->id;
$this->signed_in = true;
}
}
public function logout()
{
unset($_SESSION['user_id']);
unset($this->user_id);
$this->signed_in = false;
}
private function check_the_login()
{
if (isset($_SESSION['user_id'])) {
$this->user_id = $_SESSION['user_id'];
$this->signed_in = true;
} else {
unset($this->user_id);
$this->signed_in = false;
}
}
public function is_signed_in()
{
return $this->signed_in;
}
public function message($msg="")
{
if (!empty($msg)) {
$_SESSION['message'] = $msg;
} else {
return $this->message;
}
}
public function check_message()
{
if (isset($_SESSION['message'])) {
$this->message = $_SESSION['message'];
unset($_SESSION['message']);
} else {
$this->message = "";
}
}
}
$session = new Session();
For the sake of marking this as accepted, what you need to do is actually pass the user ID of the and not just an uninitialised variable, if your instance you are storing it in the session so I presume it would be:
<?php $user = User::find_by_id($_SESSION['user_id']); ?>
Note: To make your templating cleaner, you can use the shorthand syntax for echo:
<h1>Hello, <?= $user->username; ?></h1>
Another thing to note is that you have built a Session class, however you are still for some reason accessing the data through $_SESSION which doesn't make sense, make some setters / getters for it. Finally, sessions are something that you'll be using a lot therefore it would be worth making that class static.
Reading Material
echo

access $this in extended class

I've been following a tutorial about OOP programming. And I got this class named User:
class User {
private $_db,
$_data,
$_sessionName,
$_isLoggedIn;
public function __construct($user = null) {
$this->_db = DB::getInstance();
$this->_sessionName = Config::get('session/session_name');
if (!$user) {
if (Session::exists($this->_sessionName)) {
$user = Session::get($this->_sessionName);
if ($this->find($user)) {
$this->_isLoggedIn = true;
} else {
// Process logout
}
}
} else {
$this->find($user);
}
}
public function update($fields = array(), $id = null) {
if (!$id && $this->isLoggedIn()) {
$id = $this->data()->id;
}
if (!$this->_db->update('users', $id, $fields)) {
throw new Exception('De gegevens konden niet gewijzigd worden');
}
}
public function create($fields = array()) {
if (!$this->_db->insert('users', $fields)) {
throw new Exception('Het account is niet aangemaakt');
}
}
public function find($user = null) {
if ($user) {
$field = (is_numeric($user)) ? 'id' : 'email';
$data = $this->_db->get('users', array($field, '=', $user));
if ($data->count()) {
$this->_data = $data->first();
return true;
}
}
}
public function login($email = null, $password = null) {
$user = $this->find($email);
if ($user) {
if ($this->data()->password === hash::make($password)) {
session::put($this->_sessionName, $this->data()->id);
return true;
}
}
return false;
}
public function logout() {
session::delete($this->_sessionName);
}
public function hasPermission($key) {
$group = $this->_db->get('user_role', array('id', '=', $this->data()->rank));
if ($group->count()) {
$permissions = json_decode($group->first()->permission, true);
if ($permissions[$key] == true) {
return true;
}
}
return false;
}
public function data() {
return $this->_data;
}
public function isLoggedIn() {
return $this->_isLoggedIn;
}
}
Each user has different quicklinks stored in the database. I tried to extend the class User with class Link like this:
class Link extends User {
public static function getUserLinks($user) {
if ($user) {
$data = $this->_db->get('user_links', array('uid', '=', $user));
if ($data->count()) {
$this->_data = $data->results();
return $this->_data;
} else {
echo 'No matches found';
}
}
return false;
}
But I get an error message :
Fatal error: Using $this when not in object context in ... on line 153
I thought that when extending a class I can access all the parents details?
What am I doing wrong? Also, is my logic correct behind class Link extends User?
Thanks for the help.
you are trying to access the class pointer within a static method, that's impossible since static methods belongs to the class itself and not to the instance.
you could have a static property that will hold your instance, then you could do that like so: (You'll have to make sure you got an instance of Link)
class Link extends User {
public static $instance;
public function __construct() {
parent::__construct();
self::$instance = $this;
}
public static function getUserLinks($user) {
if (self::$instance instanceof Link && $user) {
$data = self::$instance->_db->get('user_links', array('uid', '=', $user));
if ($data->count()) {
self::$instance->_data = $data->results();
return self::$instance->_data;
} else {
echo 'No matches found';
}
}
return false;
}
}

php : Warning: Invalid argument supplied for foreach()

I just can't figure it out.. but i got a feeling the problem is around there when im throwing the exception messages. I got almost the same code in my registration class. There is just give the errors array the messages normaly like $this->errors[] = "some error".
<?php
class class_login
{
private $id;
private $username;
private $password;
private $passmd5;
private $errors;
private $access;
private $login;
private $ltoken;
public function __cunstruct()
{
$this->errors = array();
$this->login = isset($_POST['login'])? 1:0;
$this->access = 0;
$this->ltoken = $_POST['ltoken'];
$this->id = 0;
$this->username = ($this->login)? $this->filter($_POST['lusername']) : $_SESSION['username'];
$this->password = ($this->login)? $this->filter($_POST['lpassword']) : '';
$this->passmd5 = ($this->login)? md5($this->password) : $_SESSION['password'];
}
public function isLoggedIn()
{
($this->login)? $this->verifyPost() : $this->verifySession();
return $this->access;
}
public function filter($var)
{
return preg_replace('/[^a-zA-Z0-9]/','',$var);
}
public function verifyPost()
{
try
{
if(!$this->tokenValid())
throw new Exception('Invalid Form Submission!');
if(!$this->isDataValid())
throw new Exception('Ivalid Form Data!');
if(!$this->verifyDatabase())
throw new Exception('Invalid Username/Password!');
$this->access = 1;
$this->registerSession();
}
catch(Exception $e)
{
$this->errors[] = $e->getMessage();
}
}
public function verifySession()
{
if($this->sessionExist() && $this->verifyDatabase())
$this->access = 1;
}
public function verifyDatabase()
{
include('db_connect.php');
$data = mysql_query("SELECT ID FROM users WHERE username = '($this->username)' AND password = '($this->passmd5)'");
if (mysql_num_rows($data))
{
list($this->id) = #array_values(mysql_fetch_assoc($data));
return true;
}
else
return false;
}
public function isDataValid()
{
return (preg_match('/[^a-zA-Z0-9](5,12)$/', $this->username) && preg_match('/[^a-zA-Z0-9](5,12)$/', $this->password))? 1:0;
}
public function tokenValid()
{
return (!isset($_SESSION['ltoken']) || $this->ltoken != $_SESSION['ltoken'])? 0 : 1;
}
public function registerSession()
{
$_SESSION['ID'] = $this->id;
$_SESSION['username'] = $this->username;
$_SESSION['password'] = $this->passmd5;
}
public function sessionExist()
{
return (isset($_SESSION['username']) && isset($_SESSION['password']))? 1 : 0;
}
public function show_errors()
{
foreach($this->errors as $key=>$value)
echo $value."</br>";
}
}
?>
The constructor is called __construct, not __cunstruct.
I see you are setting $this->errors to an array in your __cunstruct function, but since it is not __construct it may never be set.
You need a associative array for
foreach($this->errors as $key=>$value)
But you have no one. ($this->errors[] = $e->getMessage();)
With out an associative array you must use:
foreach($this->errors as $value)
public function __cunstruct() <------ The error is probably here. It is __construct
{
$this->errors = array();
$this->login = isset($_POST['login'])? 1:0;
$this->access = 0;
$this->ltoken = $_POST['ltoken'];
$this->id = 0;
$this->username = ($this->login)? $this->filter($_POST['lusername']) : $_SESSION['username'];
$this->password = ($this->login)? $this->filter($_POST['lpassword']) : '';
$this->passmd5 = ($this->login)? md5($this->password) : $_SESSION['password'];
}
You have a typo.... _construct and not _construct

Categories