CodeIgniter - A session had already been started - ignoring session_start() - php

I keep getting this error:
A PHP Error was encountered
Severity: Notice
Message: A session had already been started - ignoring session_start()
Filename: Session/Session.php
Line Number: 140
On a page with this code:
<body>
<p>LOGIN<p>
<?php echo $this->session->userdata('Username'); ?>
</body>
There is no session_start() on the page.
The only thing I can think has caused this is in autoload.php i have done this:
$autoload['libraries'] = array('database','session');
What is causing this error?
Edit: Login controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login_controller extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('User_model','',TRUE);
}
function index() //Default function that is run when this controller is called.//
{
$this->load->helper(array('form'));
$this->load->view('Login_view');
}
function Login()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('Username', 'Username', 'trim|required');
$this->form_validation->set_rules('Password', 'Password', 'trim|required|callback_CheckDatabase');
if($this->form_validation->run() == FALSE)
{
$this->load->view('Login_view'); //Reloads the login view with validation errors if the login attempt is unsuccessful.//
}
else
{
redirect('Home_controller'); //Redirect to the homepage on successful login attempt.//
}
}
function CheckDatabase($password) //This function is only run when password validation is correct.//
{
$username = $this->input->post('Username'); //Sets the username as a $username.//
$result = $this->User_model->Login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array( //Makes an array of the data to be stored in the session.//
'UserID' => $row->UserID,
'Username' => $row->Username
);
$this->session->set_userdata('logged_in', $sess_array); //Sets $sess_array as the session.//
}
return TRUE;
}
else //Ran if the username or password aren't matched in the CIUsers database. Returns error message.//
{
$this->form_validation->set_message('CheckDatabase', 'Invalid login details.');
return false;
}
}
}
?>

Change this to
$this->session->set_userdata('logged_in', $sess_array);
this
$this->session->set_userdata($sess_array);
Example of Adding Codeigniter Session
Method 01
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
//$newdata = array(
// 'UserID' => $row->UserID,
// 'Username' => $row->Username,
// 'logged_in' => TRUE
// );
$this->session->set_userdata($newdata);
Method 02
$this->session->set_userdata('some_name', 'some_value');
// $this->session->set_userdata('my_name', 'user3574766');

This problem occurs when your PHP.INI file has session.autostart turned on. You'll need to turn this off by:
Editing your PHP.INI file and setting it to off -- or contacting your web hosting provider to do this for you
Placing a .htaccess file in the root of your web directory with the following value:
php_flag session.auto_start 0
hope this helps.

Related

Page isn't redirecting properly Codeigniter error

I am trying to learn Codeigniter,I have the following code, it gives me "The page isn't redirecting properly..." error.
public function user_login_process() {
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
$classes['class'] = $this->show_classes();
$this->load->view('header');
if ($this->form_validation->run() == FALSE) {
if (isset($this->session->userdata['logged_in'])) {
$this->load->view('admin_page', $classes);
} else {
$this->load->view('login_form');
}
} else {
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$result = $this->login_database->login($data);
if ($result == TRUE) {
$username = $this->input->post('username');
$result = $this->login_database->read_user_information($username);
if ($result != false) {
$session_data = array(
'username' => $result[0]->user_name,
'email' => $result[0]->user_email,
);
$this->session->set_userdata('logged_in', $session_data);
$this->load->view('admin_page', $classes);
}
} else {
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('login_form', $data);
}
}
}
If I comment out this line
$this->load->view('header');
The page loads properly, without the header. But whenever I try to load header it fails. The problem is not with the header I believe as it loads properly on other pages.
Some context: I am trying to make an admin panel, there is a login page and a registration page and an admin page. This code segment handles the loading of admin page after successful login. Both the login and registration page loads the header file properly.
I looked into some related questions, but could not seem to find the correct solution to this issue, since I don't know what the actual issue is.
Any help is appreciated.
In your code, redirection and view file loading is not loading. Below I have written correct code with my comments where needed.
if (isset($this->session->userdata['logged_in'])) {
redirect(base_url('YOUR_AUTHORIZED_CONTROLLER_OR_FUNCTION'));
}
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
$classes['class'] = $this->show_classes();
$this->load->view('header');
if ($this->form_validation->run() == FALSE) {
// $this->session->userdata['logged_in'] this should not be used here. Instead you should validate your controller or methods for authorized area for logged in users
$this->load->view('login_form');
} else {
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$result = $this->login_database->login($data);
if ($result == TRUE) {
$username = $this->input->post('username');
$result = $this->login_database->read_user_information($username);
if ($result != false) {
$session_data = array(
'username' => $result[0]->user_name,
'email' => $result[0]->user_email,
);
$this->session->set_userdata('logged_in', $session_data);
// Commenting below line as you should redirect to your default authorised URL
//$this->load->view('admin_page', $classes);
$this->session->set_flashdata('success', 'Great! You have successfully logged in.');
redirect(base_url('YOUR_AUTHORIZED_DEFAULT_CONTROLLER_OR_FUNCTION'));
}
} else {
$this->session->set_flashdata('error', 'Invalid Username or Password');
// Redirect to login method and controller
redirect(base_url('LOGIN_ACTION'));
}
}
View:
In your view use below line to display error/success messages. It would be better to create new view file for displaying all messages in it and load this view just after header view loaded:
<?php echo $this->session->flashdata('error'); ?>
<?php echo $this->session->flashdata('success'); ?>
Let me know if you need any clarification.

CodeIgniter Session Data not working

I'm creating a session at login but it's not saving the variables I store inside the session nor is it carrying them across to other pages:
Controller code:
function CheckDatabase($password) //This function is only run when password validation is correct.//
{
$username = $this->input->post('Username'); //Sets the username as a $username.//
$result = $this->User_model->Login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array( //Makes an array of the data to be stored in the session.//
'UserID' => $row->UserID,
'Username' => $row->Username
);
$this->session->set_userdata('logged_in', $sess_array); //Sets $sess_array as the session.//
}
return TRUE;
}
else //Ran if the username or password aren't matched in the CIUsers database. Returns error message.//
{
$this->form_validation->set_message('CheckDatabase', 'Invalid login details.');
return false;
}
}
Index function on the same controller (which should stop a user going back to the login screen but doesn't)
function index() //Default function that is run when this controller is called.//
{
if($this->session->userdata('logged_in'))
{
redirect('Home_controller');
}
else
{
$this->load->helper(array('form'));
$this->load->view('Login_view');
}
}
Code on the home view (which browser is directed to once logged in)
<?php echo $UserID .": ".$Username; ?>
I get this error for displaying the session data:
Message: Undefined variable: Username
Filename: views/Home_view.php
Line Number: 9
To retrieve the session variable, you have to do like this
$username = $this->session->userdata['logged_in']['Username'];
echo $username;
You have to retrieve it from session like this before using:
$user = $this->session->userdata('logged_in');
$Username = $user['Username'];
$UserID = $user['UserID'];
Try like this
$newdata = array(
'user_id' => $rows->id,
'user_name' => $rows->name,
'user_image' => $rows->user_image,
'user_email' => $rows->email,
'logged_in' => TRUE,
'user_type' => $rows->user_type
);
}
$this->session->set_userdata($newdata);
And check in your controller construct for user session
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class User extends CI_Controller {
public function __construct() {
parent::__construct();
//Here we will check for the session value if it is true then the function will run else it will redirect to login page
if ($this->session->userdata('logged_in') == FALSE) {
redirect(site_url('your login page'));
} else {
// if there is session value
redirect(site_url('User/your function name');
}
}
}
?>
For complete explaination read this tutorial
http://w3code.in/2015/10/session-handling-in-codeigniter/
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array( //Makes an array of the data to be stored in the session.//
'UserID' => $row[0]->UserID,
'Username' => $row[0]->Username
);
$this->session->set_userdata('logged_in', $sess_array); //Sets $sess_array as the session.//
}
return TRUE;
}

CodeIgniter: 404 Page Not Found ( In Hosting Server )

note : everything going well when I try in Localhost.
So I have a problem when I want to call my do_login controller in my login form.
this is my controller :
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Do_login extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('login_model', '', TRUE);
}
public function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'email', 'trim|required');
$this->form_validation->set_rules('password', 'password', 'trim|required|callback_check_database');
if($this->form_validation->run() == FALSE)
{
$this->load->view('admin/login_view');
}
else
{
redirect('home', 'refresh');
}
}
public function check_database($password)
{
$email = $this->input->post('email', TRUE);
$result = $this->login_model->check_login($email, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'user_id' => $row->user_id,
'email' => $row->email
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', 'Email / Password salah');
return FALSE;
}
}
}
?>
this is my view :
<?php
$attributes = array('class' => 'form-signin', 'id' => 'myform');
echo form_open('do_login', $attributes);
?>
When I try it in Localhost, everything going well and smooth.
But when I try in my web server, everytime I submit the login form, I directed into 404.
Thanks for your help :)
Check your file names Because it happens with me that different case file name was worked on localhost but not on server.
So check it once.

Session variable in Codeigniter Not Working

Hi i have created a session in Codeigniter i have set the session variable in my model. But after setting the session variable value when i call session variable in my view through Controller the session variable value becomes null. Any help???
Update
This is my Model where i set my session variable
function login ($username, $password)
{
$this->db->where('username' , $username);
$this->db->where('password', $password);
$query = $this->db->get('users');
if ($query->num_rows()>0)
{
foreach ($query->result() as $rows)
{
$data = array(
'user_name' => $rows->username,
'logged_in' => TRUE,
'validated' => true
);
}
$this->session->set_userdata($data);
//$user = $rows->username;
//$this->session->set_userdata('user_name', $user);
return true;
}
else
{
return false;
}
}
Here is my controller from where i redirect to the view
public function verification()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$result = $this->site_model->login($username, $password);
//$result = $this->session->set_userdata('validated');
if ($result)
{
//$this->admin();
//$this->session->set_userdata('login_state', TRUE);
redirect ('site/index');
}
else
{
redirect ('site/login');
//$this->load->view('login');
}
}
i have called the session_start(); in controller under construct();
and this is how i access the session variable in my view
<?php if ($this->session->userdata('user_name') != "") { ?>
.....
First of All in CI you don't need to use session_start() anywhere. only autoload session in config/autoload.php file.
Remove that session_start().
Try to use flashdata. Flashdata is temporary session mostly used in your type of case where We need to redirect user to another page and display some success or error message.
Set flashdata:
$this->session->set_flashdata('item', 'value');
get flashdata:
$this->session->flashdata('item');
Here is the documentation link http://www.codeigniter.com/user_guide/libraries/sessions.html#flashdata
use autoload applications/config/autoload.php, to add session liblary and remove session_start();
$autoload['libraries'] = array('session');
Model pass post data vithout varibles, you can do like that:
controller:
public function verification()
{
$result = $this->site_model->login();
if ($result){
redirect ('site/index');
} else {
redirect ('site/login');
}
}
Model:
public function login()
{
$this->db->where('username' , $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$query = $this->db->get('users');
if ($query->num_rows()>0)
{
$res = $query->row_array();
$data = array(
'user_name' => $res['username'],
'logged_in' => TRUE,
'validated' => true
);
$this->session->set_userdata($data);
return true;
} else {
return false;
}
}
set the session variable in controller..this works for me nice
model
function Login($email,$pass){
$this->db->where('username' ,$email);
$this->db->where('password',$pass);
$query=$this->db->get('users');
if ($query->num_rows == 1) {
return true;
}
return FALSE;
}
Controller :
function varification(){
$this->load->model('login_model');
$email=$this->input->post('email');
$pass=$this->input->post('pass');
$success=$this->login_model->Login($email,$pass);
if ($success) {
$data = array(
'user_name' => $rows->username,
'logged_in' => TRUE,
'validated' => true
);
$this->session->set_userdata($data);
redirect ('site/index');
} else{ // incorrect id or password
redirect ('site/login');
}
}
now if you echo <?php echo $this->session->userdata('user_name');?> it will show the session username. you can echo it anywhere even in the view.hope this will help you
You don't need to use the core php session_start();
Make Sure you Have loaded session library in autoload.php
as:
$autoload['libraries'] = array("session");
or you can load session library manually : as
$this->load->library('session');
For Full Documentation You can refer : Read Documentation
please use this code to set session in codeigniter
$this->session->set_userdata('user_session', $user_session_data);
I was having the same problem and it got resolved using this code.Hope it works for you too!.
Setting session variables in Model, is not a good idea for any CMV framework (like codeigniter). Edit your Model's login() function so it returns a nice set of infos ...
function login ($username, $password)
{
$this->db->where('username' , $username);
$this->db->where('password', $password);
$query = $this->db->get('users');
if ($query->num_rows()>0)
{
foreach ($query->result() as $rows)
{
$data = array(
'user_name' => $rows->username,
'logged_in' => TRUE,
'validated' => true
);
}
return $data;
}
else
{
return false;
}
}
... and handle the session from the Controller.
public function verification()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$result = $this->site_model->login($username, $password);
if ($result == false)
{
redirect ('site/login');
//$this->load->view('login');
}
else
{
$this->session->set_userdata($result);
redirect ('site/index');
}
}
Also, in order to have session's data available to the view file, you need to pass them through your controller
$data['user_name'] = $this->session->userdata('user_name');
and then you can do whatever in your view file:
<?php if ($user_name != "") { ?>
Hello i think you need to change your model code
You are setting array in session and accessing direct user_name in session
I think below code will work for you,
function login ($username, $password)
{
$this->db->where('username' , $username);
$this->db->where('password', $password);
$query = $this->db->get('users')->row();
if (count($query) > 0)
{
$this->session->set_userdata('user_name', $query->username);
$this->session->set_userdata('logged_in', true);
$this->session->set_userdata('validated', true);
return true;
}
else
{
return false;
}
}
please follow below instructions.
make sure you have addedd session lib in autoload.php file so session will automatically loaded.
When you are using session in codigniter you don't have add session_start() at the start of the file because codigniter core system will handled this automatically.
It is good idea to set session variables in controller instead of model.
I hope this helps you in solving your problem.
thanks.
Here is my solution, hope will help.. :D
in your model.. i copy paste code bellow but i change a little..
function login ($username, $password)
{
$this->db->where('username' , $username);
$this->db->where('password', $password);
$query = $this->db->get('users');
if ($query->result())//if any record
{
$rows = $query->row();
$data = array(
'user_name' => $rows->username,
'logged_in' => TRUE,
'validated' => true
);
$this->session->set_userdata($data);
return true;
}
else
{
return false;
}
}
delete your session_start() in controller,, and then in your application/config/autoload.php
in this $autoload['libraries'] = array(); => add session like this
$autoload['libraries'] = array('session');
Thankyou.. :D
user default php session, like session_start() and $_SESSION, it is working for me. in php codeignatore

unable destroy session in codeigniter

What I want to implement is a simple login page, if user login successfully, then redirect to main page, else remain login page.
I have 1 controller named login, and 1 model named main.
When user click the login button, the login/login_send will be called.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller{
function __construct() {
parent::__construct();
$this->load->model('model_login');
}
function index()
{
if ($this->model_login->is_logged_in())
{
redirect('main');
}
else
{
// load login page
$data['main'] = 'view_login';
$data['style'] = 'style_login';
$this->load->view('template', $data);
}
}
function login_send()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run() == FALSE)
{
$this->index();
}
else
{
if ( $this->model_login->validate_user() )
{
$user_session_data = array(
'username' => $this->input->post('username'),
'is_logged_in' => 1
);
$this->session->set_userdata($user_session_data);
redirect('main');
}
else
{
redirect('login');
}
}
}// end function login_send
function logout()
{
if ($this->model_login->is_logged_in())
{
$this->session->sess_destroy();
$this->session->set_userdata(array('username' => '', 'is_logged_in' => 0));
log_message('debug', 'Some variable was correctly set');
}
redirect('login','refresh');
}
}// end class Login
?>
Model_login here is just to help to verify if user is logged in, by check the session data.
<?php
class Model_login extends CI_MOdel{
function _isUserExist($username, $password)
{
$options = array(
'UserName' => $username,
'Password' => $password
);
$query = $this->db->get_where('userinfo', $options);
return $query->num_rows() > 0;
}
function validate_user()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
return ($this->_isUserExist($username, $password));
}
function is_logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if ( !isset($is_logged_in) || $is_logged_in != 1 ) return FALSE;
else return TRUE;
}
}// end class model_login
?>
When first time login, and then logout, there is no problem. However, if I login second time, I can not log out. Even the login/logout was called correctly, I also refreshed the page, but the session['is_logged_in'] == 1. Something wrong with my code?
In your application/config/config.php try changing
$config['sess_time_to_update'] = 300; //This is the default setting in ver 2.1.1
to
$config['sess_time_to_update'] = 0;
This gave me some problems a few years back

Categories