Call to member data on userdata() on a non object - php

I am getting error
Call to member data on userdata() on a non object
when i am setting the Session $this->session->userdata('userName', $userName);
Login Controller
<?php
class loginController extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('session');
}
public function login() {
$this->load->View("template/header");
$this->load->View("login_view");
}
public function AuthenticateUser() {
//Is the UserName and Password values retrieved?
if( isset( $_POST['userName'] ) && isset( $_POST['password'] ) ) {
$this->load->library("UserFactory");
$userName = addslashes($_POST['userName']);
$password = addslashes($_POST['password']);
//Get User details based on UserName and Password
$data = array(
"users" => $this->userfactory->checkLogin($userName, $password)
);
if($data["users"] != null) {
$this->session->userdata('userName', $userName);
}
header('Content-Type: application/json');
echo json_encode( $data["users"] );
}
}
}
?>
Any Idea why this is happening ?

$this->session->userdata()
this use to retrieve data from session.
to set session use this
$this->session->set_userdata('some_name', 'some_value');
Wrong Argument on here
if($data["users"] != null) {
$this->session->userdata('userName', $userName); # retrieving data
}
You trying to access data from session without setting it
Make sure you have loaded $this->load->library('session');

change
if($data["users"] != null) {
$this->session->userdata('userName', $userName);
}
to
if($data["users"] != null) {
$this->session->set_userdata('userName', $userName);
}
More on session read this http://w3code.in/2015/10/session-handling-in-codeigniter/

Related

To check login session Id after login in codeigniter

I m going to check current user id and get info is male or female but condn false
public function profile() {
$this->load->view('header');
$uname = $this->session->userdata('uname');
$row = $this->brid_groom_fetch->get_program_specific_gender();
if ($row['uname']->uname == $uname) {
$session_id = $this->session->userdata('session_id');
var_dump($session_id);
} else {
echo 'fail';
}
}
Do Not use any array object stdClass containing variable simply check both var
public function profile() {
$this->load->view('header');
// print_r($uname);
if ($this->session->userdata('logged_in')) {
//get Data from db
$row = $this->brid_groom_fetch->get_program_specific_gender();
//get session Id
$uname = $this->session->userdata();
//compare both variable directly don't use array format to compare
if ($row = $uname) {
$session_id = $this->session->userdata();
var_dump($session_id);
}
}
}

how to display home page after successfull login with codeigniter?

I tried redirect() and $this->load->view('target_page') but, no success for me so please help me with this:
My controller is here:
class Login_control extends CI_Controller {
public function index() {
$this->load->model('login_model');
$this->load->helper('url');
if(isset($_POST['Logusername'])|| isset($_POST['Logpassword']))
{
$user = $_POST['Logusername'];
$pass = $_POST['Logpassword'];
$data = $this->login_model->login1($user,$pass);
if($data > 0 )
{
echo '<font color="#00FF00">'. "OK".'</font>';
$this->load->view('testing',$data);
}
else
{ echo '<font color="#FF0000">'. "Login Failed ! Username or Password is Incorrect.".'</font>' ;
}
exit();
}
$this->load->view('signup_view');
}
}
Try this code. You have written echo before redirect so, it might not work.
class Login_control extends CI_Controller{
public function index()
{
$this->load->model('login_model');
$this->load->helper('url');
if(isset($_POST['Logusername'])|| isset($_POST['Logpassword']))
{
$user = $_POST['Logusername'];
$pass = $_POST['Logpassword'];
$data = $this->login_model->login1($user,$pass);
if($data > 0 )
{
redirect('testing');
}
else
{ echo '<font color="#FF0000">'. "Login Failed ! Username or Password is Incorrect.".'</font>' ;
}
exit();
}
$this->load->view('signup_view');
}
}
Try this
In Controller
class Login_control extends CI_Controller{
public function index()
{
$this->load->model('login_model');
$this->load->helper('url');
if(isset($_POST['Logusername']) && isset($_POST['Logpassword'])) # Change || to &&
{
$user = $_POST['Logusername'];
$pass = $_POST['Logpassword'];
$data = $this->login_model->login1($user,$pass);
if($data == 1){ # check is there only one user
echo '<font color="#00FF00">OK</font>';
$this->load->view('testing',$data);
}
else{
echo '<font color="#FF0000">Login Failed ! Username or Password is Incorrect.</font>' ;
}
}
$this->load->view('signup_view');
}
}
In Model
public function login1($user,$pass)
{
$query = $this->db->query("SELECT * FROM user WHERE username= '$user' AND password = '$pass' ");
$result = $query->result_array();
$count = count($result); # get count of result
return $count; # return count to controller
}
As you are developing in codeigniter better user its inbuilt method to get and post data. For authentication u can create one library which will be autoload and check for session like userid if not found then redirect user to login page . You can create one array in that library which will defines the public / authenticated pages on bases on which you prevent user from accessing authenticated pages. You can try this for Controller :
class Login_control extends CI_Controller
{
public function index()
{
$this->load->model('login_model');
$this->load->helper('url');
$Logusername = $this->input->post('Logusername', true);
$Logpassword = $this->input->post('Logpassword', true);
if (!empty($Logusername) && !empty($Logpassword)) {
$user = $Logusername;
$pass = $Logpassword;
$data = $this->login_model->authenticate($user, $pass);
if ($data == TRUE) {
/* User this flashdata to display the message after redirect */
$this->session->set_flashdata('success', 'Logged in successfully');
redirect(site_url("dashboard"));
} else {
/* User this flashdata to display the message after redirect */
$this->session->set_flashdata('success', 'Wrong Username/password');
redirect(site_url());
}
}
$this->load->view('signup_view');
}
}
For Model
public function authenticate($Logusername, $Logpassword)
{
$select_col = "iUserId";
$where = "`vUserName` =?"; //*
$where.=" AND BINARY `vPassword`=?";
$sql = "SELECT " . $select_col . " FROM user WHERE " . $where . "";
$result = $this->db->query($sql, array($Logusername, $Logpassword))->result_array();
if (is_array($result) && count($result) > 0) {
/* Create Session and store userid */
$this->session->set_userdata("iUserId", $result[0]["iUserId"]);
return TRUE;
} else {
return FALSE;
}
}
There are many ways to authenticate the user. Check for hooks in Codeigniter

PHP won't set session to TRUE

I'm trying to create a login system but it doesn't seem to set "Session=true". Please help I'm stuck with this for too long now.
Session starts
Checked all my code
No PHP errors
and No database Errors
Login Page:
if($session->is_logged_in()) {
redirect_to("index.php");
}
if (isset($_POST['submit'])) { // Form has been submitted.
$user_name = trim($_POST['user_name']);
$password = trim($_POST['password']);
// Check database to see if username/password exist.
$found_user = User::authenticate($user_name, $password);
if ($found_user) {
$session->login($found_user);
redirect_to("index.php");
} else {
// username/password combo was not found in the database
$message = "Username/password combination incorrect.";
}
} else { // Form has not been submitted.
$user_name = "";
$password = "";
}
Session Class:
class Session {
private $logged_in=false;
public $user_id;
function __construct() {
session_start();
$this->check_login();
if($this->logged_in) {
// actions to take right away if user is logged in
} else {
// actions to take right away if user is not logged in
}
}
public function is_logged_in() {
return $this->logged_in;
}
public function login($user) {
// database should find user based on username/password
if($user){
$this->user_id = $_SESSION['user_id'] = $user->id;
$this->logged_in = true;
}
}
public function logout() {
unset($_SESSION['user_id']);
unset($this->user_id);
$this->logged_in = false;
}
private function check_login() {
if(isset($_SESSION['user_id'])) {
$this->user_id = $_SESSION['user_id'];
$this->logged_in = true;
} else {
unset($this->user_id);
$this->logged_in = false;
}
}
}
$session = new Session();
index page:
if (!$session->is_logged_in()) { redirect_to("login.php");
Authorize Method:
public static function authenticate($user_name="", $password="") {
global $database;
$user_name = $database->escape_value($user_name);
$password = $database->escape_value($password);
$sql="SELECT * FROM users WHERE user_name='{$user_name}' AND password ='{$password}' LIMIT 1";
$result_array = self::find_by_sql($sql);
return !empty($result_array) ? array_shift($result_array) : false;
}
Change your is_logged_in() function to:
public function is_logged_in() {
$this->check_login();
return $this->logged_in;
}
Otherwise is_logged_in() will always return false on each new request (such as redirecting between pages). By calling check_login() first, it will set the logged_in variable with the value (true or false, dependent on if $_SESSION['user_id'] is set.
EDIT:
I'm sorry, I've overlooked the line in the constructor where you already call $this->check_login();
Another thing is that the authenticate function returns an Array instead of an object. So, change the following:
$this->user_id = $_SESSION['user_id'] = $user->id;
To
$this->user_id = $_SESSION['user_id'] = $user['id'];
Finally I have found the solution to this.
Guess what? It wasn't my codes fault but it was my servers(WAMP 2) fault. So, I uninstalled WAMP 2 and updated to the newer version WAMP 2.5. Solved my problem and no more getting redirect to login page!

How should I design and use an User class?

When I worked in procedural PHP programming, I would have a login page, where user's session would be created, and stored. Then, on every page, I just displayed the name of the user and retrieved the information I needed.
But I am helpless, how would you achieve this in object programming?
So, procedural (login.php):
if ( $_POST['password'] != '' && $_POST['username'] != '' ) {
// check if password&username combination exists in database etc.
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;
}
I assume it would be done like this in OOP:
// include user class
if ( $_POST['password'] != '' && $_POST['username'] != '' ) {
// check if password&username combination exists in database etc.
$user = new User();
$user->id = $userId;
$user->username = $username;
But here is the problem: Where do I create session? And this object is not going to exist outside of this "login.php" page, since I create it there. How do I make this information accessible everywhere?
And how would you get information from the database, using a special class ( let's say PDO ) without putting the queries into the user class?
Thank you very much, I just cannot understand the structure
You would do something along the lines:
class User{
private $id;
private $username;
function __construct($userId, $username) {
$this->$id = $userId;
$this->$username = $username;
}
}
if ( $_POST['password'] != '' && $_POST['username'] != '' ) {
// check if password&username combination exists in database etc.
//......
//Store your session
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;
//Create user instance
$user = new User($user_id, $username );
}
You can also put your data access layer in the user constructor, that way you just need to worry about storing the id session.
User.php:
class User{
private $id;
private $username, $first_name, $last_name;
function __construct($userId) {
$this->$id = $userId;
//get user data from db using $id
$this->$username = $row['username'];
$this->$first_name = $row['first_name'];
$this->$last_name = $row['last_name'];
}
}
Login.php:
function get_userId($username, $password)
// check if password&username combination exists in database etc.
//then return Id
//......
return $userId
}
Then use the function like the following:
if ( $_POST['password'] != '' && $_POST['username'] != '' ) {
$username = $_POST['username'];
$password = $_POST['password'];
$user_id = get_userId($username, $password);
$_SESSION['user_id'] = $user_id;
}
then you would create the user instance using the id like this:
session_start();
$user_id = $_SESSION['user_id'];
$user = new User($user_id);
Try this you are nearly there
// include user class
session_start();
if ( $_POST['password'] != '' && $_POST['username'] != '' ) {
// check if password&username combination exists in database etc.
$user = new User();
$user->id = $userId;
$user->username = $username;
$_SESSION['user_obj'] = serialize($user);
Then when you want to access it again in another page:
// include user class
session_start();
$user = new User();
if ( isset( $_SESSION['user_obj'] ) {
$user = unserialize($_SESSION['user_obj'];
}
At first you need to use official documentation
For all my experiance I can tell you that only you are decide how to use classes and OOP at all. There are many models and stadarts that gives you some structure but it is personal choices.
But in your case i can suggest to you using an regulary class that will check and store information.
class User {
private $id = null;
private $username = null;
private $isLoggedIn = false;
public function __construct() {
if (isset($_SESSION['userData']) && !empty($_SESSION['userData'])) {
// I want to think that you have more complex check for user session
$this->id = $_SESSION['userData']['userId'];
$this->username = $_SESSION['userData']['username'];
$this->isLoggedIn = true;
}
}
public function auth() {
$_SESSION['userData'] = array()
$result = false;
// Here can be an password check
if ($this->id && $this->username) {
$_SESSION['userData']['userId'] = $this->id;
$_SESSION['userData']['username'] = $this->username ;
$this->isLoggedIn = true;
$result = true;
}
return $result;
}
public function isLoggedIn() {
return $this->isLoggedIn;
}
public function userId($id = null) {
if ($id != null) {
$this->id = $id;
}
return $this->id;
}
public function userName($name = null) {
if ($name != null) {
$this->name = $name;
}
return $this->name;
}
}
And usage for this class will be short and easy
// include user class
session_start();
$user = new User();
if ($user->isLoggedIn()) {
// user is Logged In
} elseif ( $_POST['password'] != '' && $_POST['username'] != '' ) {
// check if password&username combination exists in database etc.
$user->userId($userId);
$user->userName($username);
$user->auth();
} else {
echo 'Auth failed';
die();
}
echo 'Hello, ' . $user->userName();

Cannot exit in CodeIgniter constructor

I'm basically trying a session control. If the user is logged in, it's ok to move on. But if he's not logged in, then it will show a log-in screen and then die. However, when I use die or exit in the constructor, it does not show the log-in screen; it immediately dies. The code is as following:
private $username = null;
private $mongoid = null;
private $neoid = null;
public function __construct(){
parent::__construct();
// session to global
$this->username = $this->session->userdata( 'username');
$this->mongoid = $this->session->userdata( 'mongoid');
$this->neoid = $this->session->userdata( 'neoid');
// check if user is logged in
if( $this->username == "" || empty( $this->username)){
$this->load->view( 'access/login');
die;
}
}
It shows the log-in page if die is not written there, but with die, it does not show. Why do I want to use die? Because if I don't use, it moves on the index function and I don't want it to execute index function if the user is not logged in.
What is wrong here? What should I use to stop executing?
CodeIgniter does not instantly output the view when you load it with $this->load->view();, it puts the output of the view to the output buffer instead and after everything is loaded it flushes the whole output to the user. With that said, the problem you are seeing is that it buffers the output, then it dies without flushing it.
die is really bad and should not be used outside debugging, you should better use something like a variable switch. If it's only for the controllers scope, then you can make a
private $show_everything_else = true;
In the constructor:
if( $this->username == "" || empty( $this->username)){
$this->load->view( 'access/login');
$this->show_everything_else = false;
}
In any of the controller's methods:
if($this->show_everything_else) {
// ...
}
In any case, this solution is a quick fix and there are much better possibilities how to do this, but all of them require a different approach.
You can have a method and call it in constructor:
function __construct() {
parent::__construct();
$this->_is_logged_in();
}
and the method should look like this:
function _is_logged_in() {
$is_logged_in = $this->session->userdata('is_logged_in');
if (!isset($is_logged_in) || $is_logged_in != true) {
redirect('login');
die();
}
}
And, of course, you should have controller for login, which can look like this:
<?php
class Login extends CI_Controller {
function index() {
$this->load->view('LOGIN-VIEW');
}
function validate() {
$this->load->model('login_model');
$data = $this->login_model->validate();
if ($data != false) {
$data['is_logged_in'] = true;
$this->session->set_userdata($data);
redirect('MAIN-CONTROLLER-AFTER-LOGIN');
}
else {
$this->index();
}
}
function logout() {
$this->session->sess_destroy();
$this->index();
}
}
This what i posted, also preserve sessions in database.
Login model can be as primitive as this:
class Login_model extends CI_Model {
function validate() {
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get('users');
if($query->num_rows == 1) {
$data = $query->row_array();
return $data;
} else {
return false;
}
}
The Controller class will automatically run the index() function. So, to make it work, you must return the index() if the login check in construct is failed. Here what you can do:
private $username = null;
private $mongoid = null;
private $neoid = null;
private $no_login = false;
public function __construct(){
parent::__construct();
// session to global
$this->username = $this->session->userdata( 'username');
$this->mongoid = $this->session->userdata( 'mongoid');
$this->neoid = $this->session->userdata( 'neoid');
// check if user is logged in
if( $this->username == "" || empty( $this->username)){
$this->load->view( 'access/login');
$this->no_login = true;
}
}
function index(){
if($this->no_login) return;
// another statement if login success.....
}

Categories