My session always loses data when redirecting - php

Every time I login, in the model the session receives all the data correctly, but when the page is redirected to the home, the session data disappears.
I'm using codeigniter, and this is the model code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct()
{
parent::__construct();
if (isset($_SESSION['id_usuario']))
redirect(base_url());
$this->load->model('blogueiro_model');
$this->load->model('pagina_model');
$this->load->library('form_validation');
}
public function index()
{
$this->load->view('login.php');
}
public function checa()
{
if ( ! $this->input->post())
show_404();
$this->form_validation->set_rules('login', 'login', 'required');
$this->form_validation->set_rules('password', 'password', 'required');
$login = html_escape($this->input->post('login'));
$senha = html_escape($this->input->post('password'));
if ($this->form_validation->run() === TRUE)
{
$usuario = $this->blogueiro_model->autentica($login, $senha);
if ($usuario !== NULL)
{
$this->session->set_userdata('id_usuario', $usuario->id);
$this->session->set_userdata('nome_usuario', $usuario->nome);
$this->session->set_userdata('login_usuario', $usuario->login);
$this->session->set_userdata('e_admin', $usuario->e_admin);
$this->session->set_userdata('foto', $usuario->foto);
$permissoes = ($usuario->e_admin == 0) ? $this->blogueiro_model->busca_permissoes($usuario->id) : $this->blogueiro_model->lista_todas_permissoes();
$this->session->set_userdata('permissoes', $permissoes);
$this->blogueiro_model->limpa_trials($login);
}
else
{
$this->blogueiro_model->incrementa_trials($login);
$this->index();
}
}
else
{
$this->index();
}
redirect(base_url());
}
}
Another thing I noticed was that the status code is always between 302 and 303, I researched a lot but found no solution to this problem.
Follow the status, preview and request images.
Status Code: 302 found
Preview
Request

Are you using Ci3 ?
Are you loading the session library in the controller that has the method that shows the "home".
You can load the library in the controller or methods like this: $this->load->library('session'); or you just can auto load the session library everywhere
adding the session library in application/config/autoload.php.
For more please check Auto loading in CodeIgniter 3

Try like this
$_SESSION['id_usuario'] = (int) $usuario->id;
$_SESSION['nome_usuario'] = (string) $usuario->nome;

Related

"The page isn’t redirecting properly" error in codeigniter

i tried to check if user has session in login page, if he has session and role id this controller will redirect to certain controller. but it gave me error "The page isn’t redirecting properly" instead.
here's my code
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Auth extends CI_Controller
{
public function __construct()
{
parent::__construct();
if (!$this->session->userdata('username') == null) {
if ($this->session->userdata('role_id') == 1) {
redirect(base_url('back/admin'));
} else {
redirect(base_url('back/user'));
}
} else {
redirect(base_url('back/auth'));
}
}
public function index()
{
$data = ['title' => 'Log-in page'];
$this->form_validation->set_rules('un', 'Username', 'required|trim');
$this->form_validation->set_rules('pw', 'Password', 'required|trim');
if ($this->form_validation->run() == false) {
$this->load->view('back/login', $data);
} else { }
}
public function logout()
{
$this->session->unset_userdata('username');
$this->session->unset_userdata('role_id');
$this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">you\'re session has been deleted</div>');
redirect(base_url('back/auth'));
}
public function errorp()
{
// $this->load->view('back/error');
echo 'not authorized';
}
}
i tried many things to solve this redirect error, but still can't find way how to fix this or the way i'm redirect was wrong ?
certainly, there is an error in logout function.
Try fixing it:
(before)
'<div class="alert alert-success" role="alert">you're session has been deleted</div>'
(after)
'<div class="alert alert-success" role="alert">you\'re session has been deleted</div>'
i got the solution for this error
i need to check the session inside my index, no need to check inside __construct, it keep redirecting to the same controller that's why i got that error.

Page is not redirecting to URL?

I'm working on PHP-CodeIgniter project. I'm using ION Auth library for authentication.
My question is when I'm copy paste table data to Excel sheet, and then click on links copied to excel are not properly redirect to particular page. If I hover mouse on the link it shows proper address, but while clicking on it then it redirects to Dashboard not to particular page, their is a Active session data, but it redirects to Dashboard only.
Controller code:
<?php (defined('BASEPATH')) OR exit('No direct script access allowed');
class Auth extends CI_Controller
{
function __construct()
{
parent::__construct();
// $this->load->library('');
$this->load->model('Landlord_m', 'l');
}
public function index()
{
redirect('auth/login');
}
public function login()
{
if( $this->ion_auth->logged_in() ) redirect('dashboard');
$this->form_validation->set_rules('email', 'email', 'required|valid_email|trim');
$this->form_validation->set_rules('password', 'password', 'required|trim');
$this->form_validation->set_message('required', 'Please enter your %s');
// Validate form
if( $this->form_validation->run() )
{
$remember = (bool) $this->input->post('remember');
// Check login
if( $this->ion_auth->login($this->input->post('email'), $this->input->post('password'), $remember) )
{
// Login was successful
redirect('dashboard', 'refresh');
}
else
{
// Login was un-successful
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect('auth/login', 'refresh');
}
}
else
{
$data['message'] = $this->session->flashdata('message');
$this->load->view('auth/login', $data);
}
}
public function logout()
{
if( $this->ion_auth->logout() )
redirect('auth/login');
else
die("There was an error logging you out");
}
Any kind of help is welcome, Thanks in advance.

PHP login using Ion Auth and Facebook login works locally on MAMP but not Web Server

The problem I'm facing is that manual new user subscription works locally but does not work on remote web server. The only difference between the non-working one and the one that works is that I upgraded Ion Auth to version 2 and added Facebook-Ion Auth library for Facebook Login.
Again, it works perfect locally, but not on the web server. PHP versions have been tested and work fine.
Here's the controller it gets stuck on (shows a blank page or goes back to homepage).
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Signup extends CI_Controller {
function __construct()
{
parent::__construct();
$this->CI =& get_instance();
$this->load->library('form_validation');
$this->load->helper('url');
$this->load->library('forms/signupform');
$this->form_validation->set_error_delimiters(
$this->config->item('error_start_delimiter', 'ion_auth'),
$this->config->item('error_end_delimiter', 'ion_auth')
);
}
/**
* #signup page of freelancer
*/
public function index()
{
$data['title'] = lang('title_registration');
$data['bodyclass'] = 'hold-transition register-page';
$data['js_bottom_files'] = array('plugins/iCheck/icheck.min', 'js/custom');
$data['cssfiles'] = array('plugins/iCheck/square/blue');
// POST SIGNUP FORM
if ('POST' == $this->input->server('REQUEST_METHOD') && $this->input->post('registersubmit') ) {
// Signup Action
$data['message_success'] = $this->signup();
}
// $user['checked'] = '';
// if ($this->input->post('agree') == 'yes') {
// $user['checked'] = 'checked';
// }
$data['form'] = $this->signupform->view($user);
//Render Or redirect according to User AccessLevel
if (!$this->ion_auth->logged_in()) {
$this->template->load('layout', 'home', $data);
} elseif ($this->ion_auth->is_admin()) {
redirect(site_url('admin/dashboard'), 'refresh');
} elseif ($this->ion_auth->is_members()) {
redirect(site_url('note/create'), 'refresh');
}
}
/**
* #Signup action for user
*/
public function signup()
{
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
// $this->form_validation->set_rules('full_name', lang('label_full_name'), 'required');
$this->form_validation->set_rules('loginPassword', lang('label_signup_createpassword'), 'required|min_length['.$this->config->item('min_password_length', 'ion_auth').']|max_length['.$this->config->item('max_password_length', 'ion_auth').']');
// $this->form_validation->set_rules('confirmpassword', lang('label_signup_confirmpassword'), 'required');
// $this->form_validation->set_rules('agree', 'Agree', 'required');
if ($this->form_validation->run() == true) {
$email = $this->input->post('email');
$password = $this->input->post('loginPassword');
// $additional_data = array('first_name' => $this->input->post('full_name'), 'school' => $this->input->post('school_name'));
$group_ids = array( 'user_groups' => 2);
if ($this->ion_auth->register($email, $password, $email, $additional_data, $group_ids)) {
//check to see if we are creating the user
//$this->session->set_flashdata('message_success', $this->ion_auth->messages());
//redirect(site_url('/'), 'refresh');
if($this->ion_auth->login($email, $password)){
redirect(site_url('note/create'), 'refresh');
}
} else {
$this->session->set_flashdata('message_error', $this->ion_auth->errors());
redirect(site_url('/'), 'refresh');
}
}
}
}
/* End of file signup.php */
Potentially not the issue without more information but:
$group_ids = array( 'user_groups' => 2); should just be $group_ids = array('2')
See usage of the register function here.
and in the Ion auth config file $config['identity'] should be set as email (if you haven't done so already).

How Deny many users logging with same user in codeigniter?

i have problem with my app " multi user can logging same user i need to prevent this problem i hope to help me
my code :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller {
public function index()
{
$posts = $this->input->post();
$name = $this->input->post('name');
$pass = $this->input->post('pass');
if(isset($posts['submit']))
{
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'name ', 'trim|required');
$this->form_validation->set_rules('pass', 'pass ', 'trim|required');
if($this->form_validation->run())
{
$this->load->model("users_model");
$res = $this->users_model->auth($name,$pass);
if(!empty($res))
{
foreach($res as $r)
{
if($r->active == 0)
{
$err = '<h4 class="alert alert-danger"> error loggin
To make sure that a user doesnt login twice you could store the sessions in the database and then check on login if the user is logged in. If so, remove the old user and allow login or maybe show a confirm message whether to terminate the remaining session or not. What i recommend is to make the session automatically expire.
My suggestion is to better write the separate controller for login.Your login controller should like this below,
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Controllername extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model("users_model");
if(!empty($this->session->userdata('userid');))
{
/*if any try to login again if they already logged in make them to redirect to
any other page you want*/
}
}
public function login()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'name ', 'trim|required');
$this->form_validation->set_rules('pass', 'pass ', 'trim|required');
if($this->form_validation->run())
{
$res = $this->users_model->auth($name,$pass);
if(!empty($res))
{
//if the userdata matches then set the session while login
$this->session->set_userdata('userid', $res[0]->userid );
//after login redirect the user to where you want
}
}
}
}
By checking the session as not empty it prevent the user to login again.Whenever user try to login it checks for the session is empty or not in constructor.If the session is not there then it normally goes to login function.If the session is already set then it redirects to any other page you want.

Codeigniter $this->load->view to a Particular Section of page (Data-Toggle - Tab)

I have this admin panel where I use different data-toggle tabs.
In CI(3), if I go with redirect('user/dashboard#new'); , it redirects me to correct section of view but not with form_validation errors.
And if I try $this->dashboard('user/dashboard#new'); it renders the errors but leads me to the wrong section of page (not at #new).
I have just started developing with CI and looking for some help from seniors.
Thanks in advance.
Controller (user)
public function dashboard() {
if($this->session->userdata('is_logged_in')){
$data['homepage'] = '../../templates/vacations/users/dashboard';
$this->load->view('template_users',$data);
}else{
$data['session_error']='Either the session has expired or you have tried to access this page directly';
$this->load->view('../../templates/vacations/headfoot/header-login');
$this->load->view('../../templates/vacations/users/session-error', $data);
$this->load->view('../../templates/vacations/headfoot/footer-login');
}}
Form Validation
if($this->form_validation->run() == FALSE)
{
$this->dashboard('user/dashboard#new');
} else {
$this->load->model('model_users');
if($query = $this->model_users->insert_property_details())
{
redirect('user/dashboard#new');
} else {
redirect('user/dashboard#new');
}}}
$this->dashboard('user/dashboard#new'); just runs/calls the method within the current page. 'user/dashboard#new' does nothing because the method is not written to accept arguments anyway:
public function dashboard(/* arguments would be here normally */) { ... }
Redirecting right after running validation won't work because you will lose the validation errors when you load a new page.
You need to save the errors somewhere, such as to session data, then redirect to dashboard, and then load the errors from saved location and display them on the dashboard view.
Here's an example using session data.
Form method:
if($this->form_validation->run() == FALSE)
{
$this->session->set_userdata('validation_errors', validation_errors());
$this->session->mark_as_flash('validation_errors'); // data will automatically delete themselves after redirect
redirect('user/dashboard#new');
}
else { ... }
Dashboard method:
public function dashboard()
{
if($this->session->userdata('is_logged_in')){
$data['validation_errors'] = $this->session->userdata('validation_errors');
$data['homepage'] = '../../templates/vacations/users/dashboard';
$this->load->view('template_users',$data);
} else { ... }
}
Getting error array from form validation class (for comments below):
class MY_Form_validation extends CI_Form_validation {
public function error_array()
{
return $this->_error_array;
}
}

Categories