CodeIgniter session Data showing null during authentication - php

I'm trying to send the session variable to another controller but when i use r_print() it shows nothing and there is condition applied which returns null.
<?php
// library/login_lib.php
class Login_lib
{
public function logged_in()
{
$CI = & get_instance();
return ($CI->session->userdata('userdata')['is_logged_in'])
? $CI->session->userdata('userdata')['is_logged_in'] : Null;
}
}
?>
<?php
// another file common_helper.php
if( !function_exists('authentication_user') )
{
function authentication_user()
{
$CI = & get_instance();
if( !$CI->login_lib->logged_in() )
{
$CI->session->set_flashdata('error', 'Please login with username and password');
if( $CI->input->is_ajax_request() )
{
echo 'session_expire';
die();
}
else
{
redirect();
}
}
}
}
There is another controller called Dashboard where i calling the above function authentication_user(). What i want now i want to call true from the login_lib which i am not actually. I don't know why its blocking to view the Login session.
Thanks in advance

return $CI->session->userdata('is_logged_in') ? $CI->session->userdata('is_logged_in') : Null;
syntax for getting session data in codeigniter is
$this->session->userdata('session_key');

Related

accessibilty issue with codeigniter session library

I'm working on user login system in codeigniter. When user clicks on login button the username and password are verified and the data is store in $this->session->set_userdata($arr); session library and the page redirects to home.php. Till here works fine but when is try to access the session in home.php as print_r($this->session->userdata);. it give me this errors
Here is the Controller code : Login.php
function login_user(){
$login_btn = $this->input->post('login_btn');
if($login_btn == TRUE){
$arr['login'] = array(
'username'=>$this->input->post('username'),
'password'=>$this->input->post('password')
);
$query = $this->Login_model->users_login($arr);
if($query->num_rows() > 0 && $query->num_rows() == 1){
$this->load->library('session');
$this->session->set_userdata($arr);
redirect('Login/redirec_To_home','refresh');
}
else
{
$this->index();
}
}
else
{
$this->index();
}
}
function redirec_To_home(){
$this->load->view('login/home');
}
Here is the view html file name : path views/login/home.php
<?php
print_r($this->session->userdata); //ERRORS SHOWN IN THIS LINE NUMBER : 13
?>
THANKS IN ADVANCE
Please go to application/config/autoload.php in your project directory and search libraries, after that add session to this line which will look like this.
$autoload['libraries'] = array('session');
In the __construct area you need to reload the session library using get instance in libraries
https://www.codeigniter.com/user_guide/general/ancillary_classes.html
https://www.codeigniter.com/user_guide/general/creating_libraries.html#utilizing-codeigniter-resources-within-your-library
class Example {
protected $CI;
// We'll use a constructor, as you can't directly call a function
// from a property definition.
public function __construct()
{
// Assign the CodeIgniter super-object
$this->CI =& get_instance();
$this->CI->load->library('session');
$this->CI->load->model('login_model');
}
public function somefunction()
{
$this->CI->input->post('username');
$this->CI->input->post('password');
$user_model = $this->CI->login_model->user_login();
$sesstion_data = array('user_id' => '1');
$this->CI->session->set_userdata($sesstion_data);
}
}

Fatal error: Call to a member function login() on a non-object in

Got an issue with a web app that I've inherited as a project and unfortunately I can't trace the error. It seems that the model isn't being loaded but I could be wrong. Any help would be great.
code is:
public function login()
{
//If request is post then user is trying to login, so process the login info
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//Run the model method ::login
$login_successful = $this->User->login();
// check login status
if($login_successful) {
// if YES, then move user to dashboard/index (btw this is a browser-redirection, not a rendered view!)
header('location: ' . URL . 'passwords/index');
} else {
echo "Incorrect user / pass combination entered. Please try again.";
}
}
}
and the model function is:
public function login() {
$username = $_POST['data']['User']['username'];
$password = $_POST['data']['User']['password'];
$bind = array(
":username" => "$username",
);
$result = $this->select("users", "username = :username", $bind);
//Check the password returned from the db against the password entered
if (Bcrypt::checkPassword($password, $result[0]['password']) == true) {
Session::init();
Session::set('user_logged_in', true);
Session::set('user_id', $result[0]['id']);
Session::set('user_name', $result[0]['username']);
Session::set('user_permission', $result[0]['permission']);
Session::set('user_role', $result[0]['role']);
return true;
} else {
return false;
}
}
also I've noticed that the controller and model both have a function called login.]
Thanks
The reason is $this->User is not a valid class instance.
Make sure that it is an object.
Try
var_dump($this->User);
die();
//Run the model method ::login
$login_successful = $this->User->login();
And you will see that there is no instance there.
What to do?
Find the place where you expect your model being initialized. Check, why it is not.

Session in Yii application

I want to learn sessions in Yii, thus I created a simple login form. Also I want to "set" session in this project.
My login action
public function actionLogin()
{
Yii::app()->session['userid'] = "value"; // where i should put line ??
$model=new LoginForm('login');
if(isset($_POST['ajax']) && $_POST['ajax']==='form-reg')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
if(isset($_POST['regist']))
{
$model->username=$_POST['istiad'];
$model->password=$_POST['parol'];
if($model->validate() && $model->login()) {
$this->redirect(array( 'update','id'=>$this->getIdByUsername($model->username ) ));
/* $this->render(
'update',array(
'model'=> $this->loadModelByUsername($model->username ) ) );*/
}
}
else
$this->redirect(Yii::app()->user->returnUrl);
}
logout action
public function actionLogout()
{
Yii::app()->user->logout();
unset(Yii::app()->session['userid']); // also this,
Yii::app()->session->clear(); // this
Yii::app()->session->destroy(); // and this line ??
$this->redirect(Yii::app()->homeUrl);
}
p.s: PLEASE EXPLAIN ME what is the userid in unset(Yii::app()->session['userid']); ? I couldn't understand (because I'm new in Yii). It's just only a variable or any attribute of the db table name?
I copied the lines from this topic.
Thanks. Best regards.
Set session after validation user name and password. Like here..
if($model->validate() && $model->login()) {
Yii::app()->session['userid'] = "value"; //here
$this->redirect(array( 'update','id'=>$this->getIdByUsername($model->username ) ));
}
unset destroys the specified variable.
unset(Yii::app()->session['userid']);
Here userid is session variable. It is destroyed.
Yii::app()->session->clear();
clear() is used to remove all sessions.
After clear(), you need to remove actual data from server using
Yii::app()->session->destroy();

Kohana/PHP Auth fails while issusing a request through AJAX

I have a base class which is inherited by all the controllers. I am having a function in the base class which determines the logged in users role using Auth. Once the users role is determine a variable $LoggedIn_role is set.
This method is correctly called on the initial page load, but later i am issuing ajax calls to check whether the user is still logged in, at that time the Auth::logged_in() always returning 0.
The kohana version i am using is 3.3
Can any one please suggest what is the best approach to circumvent this issue. Thanks.
To login -
if ($ValidObj->check()) {
if (Auth::instance()->login($_POST['email'], $_POST['password'],FALSE)) {
$this->DoPostLoginJobs();
} else {
$this->ManageError(Controller_Application::MsgWrongUserCredentials);
}
} else {
$this->Form_Errors = $ValidObj->errors('');
}
To Logout -
public function action_logout() {
$loggedout = Auth::instance()->logout();
if ($loggedout)
HTTP::redirect ('/home/'); // redirects to the home page.
}
Inside the controller_Application . The base class of all the controllers
public function DetermineUserRole() {
$this->LoggedIn_Role = Controller_Application::None;
try {
if (Auth::instance()->logged_in('freelancer')) {
$this->LoggedIn_Role = Controller_Application::Freelancer;
$this->LoggedIn_Id = Auth::instance()->get_user()->pk();
} else if (Auth::instance()->logged_in('employer')) {
$this->LoggedIn_Role = Controller_Application::Employer;
$this->LoggedIn_Id = Auth::instance()->get_user()->pk();
}
} catch (Gettrix_Exception $exc) {
$this->ManageError(Controller_Application::RedirectNonRecoverableError);
}
public function before() {
if ($this->request->is_ajax()) {
$this->auto_render = false;
}
$this->DetermineUserRole();
if($this->auto_render==TRUE){
parent::before();
$this->template->content = '';
$this->template->styles = array();
$this->template->scripts = array();
View::set_global('site_name', 'TheWebTeam');
View::bind_global('Form_Errors', $this->Form_Errors);
View::bind_global('LoggedIn_Role', $this->LoggedIn_Role);
View::bind_global('LoggedIn_Id', $this->LoggedIn_Id);
View::bind_global('InvitedEmail', $this->InvitedEmail);
View::bind_global('InvitedUniqueID', $this->InvitedUniqueID);
View::bind_global('scripts', $this->template->scripts);
View::bind_global('styles', $this->template->styles);
}
//This is inside the Home page controller, where it lists all the jobs for the logged in user.
public function action_joblist()
{
echo Auth::instance()->logged_in() . //The state holds to the initial state, doesn't //change when the user is logged out or logged in.
}
Please note that action_joblist() is called via AJAX/Jquery call.
The issue is fixed by following the instructions given in the link : http://forum.kohanaframework.org/discussion/9619/session-timeout-corruption-problems/p1

codeigniter form validation doesn't call callback function

By some reason form validation doesn't call callback function which I set in the rules.
It is rules sets
if( ! empty($_POST))
{
ci()->form_validation->set_rules('login', 'Username', 'trim|required');
ci()->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|callback_check_email');
if (ci()->form_validation->run() == TRUE)
{
}
}
and a function
public function check_email($str)
{
ci()->load->model(array('secure_model', 'admin/members_model'));
$o['username'] = ci()->input->post('login');
$o['email'] = ci()->input->post('email');
$m = $this->_model->get_row($o);
if ( ! $m)
{
$this->form_validation->set_message('check_email', lang('unlock_incorrect_login'));
return FALSE;
}
else
{
return FALSE;
}
}
I set FALSE twice to see if it call callback function but it doesn't display error message. So I suppose CI doesn't try to call it. What is wrong?
In your check_email() function, you're using $this->form_validation instead of ci()->. I'm not sure why you're using ci() instead of the standard CI way of using $this but that's the part in your code which seems off compared to the rest.

Categories