CodeIgniter 3 session regenerated after login in Firefox - codeigniter

After login, I set session with user id and some information. It works very well on Google Chrome.
But it is redirect to login page after login on Firefox. I don't know what is the problem. Furthermore, the strange issue is this is working well on my local server like 127.0.0.4. This redirect issue is occurred on live server(hostinger) and only on Firefox.
Here is my config.php
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'eq_session';
$config['sess_expiration'] = 7200;
$config['sess_encrypt_cookie'] = TRUE; // JFRH
$config['sess_table_name'] = 'eq_sessions'; // JFRH
// $config['sess_save_path'] = NULL;
$config['sess_save_path'] = FCPATH . 'public/sess';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
$config['sess_match_useragent'] = FALSE;
And this function is customized library for authentication.
public function sess_validate($redi = FALSE, $sess_upda = FALSE) {
$CI =& get_instance();
if ($CI->session->userdata('sess_id')) {
//Preguntar si la variable de sesiĆ³n 'usua' existe o si se requiere
//que los datos de la misma sean actualizados
if ((!$CI->session->userdata('usua')) || ($sess_upda == TRUE)) {
$this->__sess_update();
}
return TRUE;
} else {
if (!$redi) {
return FALSE;
} else {
print "<script> window.location.href = '". base_url('auth')."'; </script>";
}
}
}
I set session data in my Auth Controller like this.
$this->session->set_userdata('sess_id', $usua->id_usu);
$this->session->set_userdata('sess_na', $usua->nom_usu . " " . $usua->ape_usu);
$this->session->set_userdata('sess_log', $usua->log_usu);
I have tested with changed session path.

I have fixed this.
Here are my config.php.
$root = "http://".$_SERVER['HTTP_HOST'];
As you can see, I was set the root like above line.
It works on my local server but server protocol was https when I deploy this on server. It is a cause of this problem.
So I fixed this like this.
$protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === 0 ? 'https://' : 'http://';
$root = $protocol . $_SERVER["HTTP_HOST"];
$root .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
$config['base_url'] = $root;
Now, works fine.

Related

why in Codeigniter my session lost in other pages?

it's first time I use Codeigniter 3.x. after authentication for login I set session data in Login_model.php:
$data_session = array(
'PersonId' => $PersonId,
'PersonEmail' => trim($PersonEmail),
'PersonName' => trim($PersonName),
'PersonFamily' => trim($PersonFamily),
'Login' => true);
$this->session->set_userdata($data_session);
before redirect I have access to my session data by :
print_r($this->session->userdata());
Array([__ci_last_regenerate] => 1510383844 [PersonId] => 129[PersonEmail]=> h#q.com [PersonName] => PersonName [PersonFamily] => PersonFamily [Login] => 1)
but after redirect my session data is something like this:
Array( [__ci_last_regenerate] => 1510384212)
also my setting in config.php is:
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'east';
$config['sess_expiration'] = 7200;
//$config['sess_save_path'] = sys_get_temp_dir();
$config['sess_save_path'] = 'ci_sessions';
$config['sess_match_ip'] = TRUE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
//------------------
$config['cookie_prefix'] = '';
$config['cookie_domain'] = 'domain/admin/';
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;
I have reviewed a lot of things in this regard. but I still have not gotten a good result.
when using
$config['sess_driver'] = 'files';
then $config['sess_save_path'] must be set to the absolute path of the folder where session files are stored.
With this folder structure
webroot/
application/
sessions/
system/
...etc/
Then
`$config['sess_save_path'] = FCPATH."sessions/";`
will work perfectly.
Folder write permissions must be set appropriately.
EDIT
You should try setting $config['cookie_domain'] = ''; (an empty string) and if that does not work try $config['cookie_domain'] = '.your-domain.com';
The following controller will allow you to test if sessions are working correctly. Create a file named Test_sessions.php in your controllers folder.
Use this code.
<?php
/**
* This class is useful for testing the configuration of the CodeIgniter "session" library.
* It works only for CodeIgniter versions >= 3.0.0
*
* If "session" is properly configured then each time you ask a browser for this page
* the display will alternate between "No session data" and the value of $this->sess_message.
*/
defined('BASEPATH') OR exit('No direct script access allowed');
class Test_sessions extends CI_Controller
{
/**
* #var string So you can define your own message to be displayed.
*/
public $sess_message;
function __construct()
{
parent::__construct();
// The next line can be commented out if 'session' is autoloaded - or not, doesn't matter.
$this->load->library('session');
$this->sess_message = "We got session data!";
}
public function index()
{
echo date("F j, Y, g:i:s a")."<br>"; //so you can tell the page actually does refresh
if($this->session->testing)
{
echo $this->session->testing;
unset($_SESSION['testing']);
}
else
{
echo "No session data";
$_SESSION['testing'] = $this->sess_message;
}
}
}
Browse to http://yoursite.com/test_sessions. If sessions are properly configured, every time you refresh the page it will alternate between the two messages.
I solved my problem by change my config to:
$config['sess_driver'] = 'files';$config['sess_cookie_name'] = 'ci_session';$config['sess_expiration'] = 86400;$config['sess_save_path'] = FCPATH.'sessions/';$config['sess_match_ip'] = FALSE;$config['sess_time_to_update'] = 3600;$config['sess_regenerate_destroy'] = TRUE;$config['cookie_prefix'] = '';$config['cookie_domain'] = '';$config['cookie_path'] = '/';$config['cookie_secure'] = FALSE;$config['cookie_httponly'] = FALSE;

Retrive some data store in session with codeigniter

I need to store some data that i get via an ajax request on a method, and later retrive them when i call another method.
public function updateInt()
{ $this->load->library('session');
$interval = $this->input->post('_interval');
$aInt = array('my_interval' => $interval);
$this->session->set_userdata('post', $aInt);
$_interval_ = $this->session->userdata['post']['my_interval'];
return $_interval_;
}
public function getInt()
{
$interval = $this->updateInt();
// print $interval and do some stuff !!
}
// This return a null, but I need the value set on the front-end by the user and passed with an ajax call to updateInt() method.
I need some help because I'm newbie with codeignter.
Make sure you have set your sessions in your config.php do not leave the session save path null
Example
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = APPPATH . 'cache/session/';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
Make sure session folder permission 0700
Make sure you are getting correct post data what your after
public function updateInt()
{
// You can autoload it in config/autoload.php saves loading every page
$this->load->library('session');
$aInt = array('my_interval' => $this->input->post('_interval'));
$this->session->set_userdata('post', $aInt);
// Use `(` and `)` not `[]`
$interval = $this->session->userdata('post');
return $interval;
}
public function getInt()
{
$interval = $this->updateInt();
// Test
echo $interval['my_interval'];
// print $interval and do some stuff !!
}

session_id in codeigniter returns nothing

My CI_VERSION is 3.0.6.
now I want to echo session_id, but it returns nothing!
class MainIndex extends BaseController
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->library->load('session');
echo $this->session->userdata('session_id');
return ;
...
my config:
$config['sess_driver'] = 'files';
$config['sess_save_path'] = BASEPATH . 'soheil/files_cache/';
$config['sess_valid_drivers'] = array();
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 68400;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = FALSE;
$config['sess_table_name'] = 'ci_session';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 68500;
Try to print all session data using.
Also make sure that you have loaded session in config/autoload.php
$autoload['libraries'] = array('session');
print_r($this->session->all_userdata());
also in order to use the session you are require to add some string in $config['encryption_key']
Just having a read in the Codeigniter user guide, it makes mention that session_id is no longer available via the sessions library since "sometime ago" (My Words, not theirs...)
The alternative they recommend is session_id().
Give that a shot!

one codeigniter application folder run two website with different domain

could i use one codeigniter framework directory to create multiple applications?
I have two website with one CodeIgniter application, i am used one DB for both of website, system folder, config, view, controller etc are also same.
main website is working fine, all links are working and another website only home page is working, rest of the links are not working, when i am open another link the error is occur: "Unable to load your default controller. Please make sure the controller specified in your Routes.php file is valid." version of codeigniter is 2.2.0, please help.
Thanks in advance
Try this:
ex:
- subdomain1.hostname.com
- subdomain2.hostname.com
then in my front index:
// Host address
$host = $_SERVER['HTTP_HOST'];
$SERVER_NAME = $_SERVER['SERVER_NAME'];
define('HOST', $SERVER_NAME);
// Extract eventual subdomain
$host3 = strrpos($host, '.');
$host2 = substr($host, 0, $host3);
$host1 = strrpos($host2, '.');
$subdomain = substr($host, 0, $host1);
if($host == 'localhost') {
define('HOST_TYPE', 'localhost');
define('SUBDOMAIN', FALSE);
} else {
if($subdomain !== 'www' && $subdomain !== '') {
define('HOST_TYPE', 'subdomain');
define('SUBDOMAIN', $subdomain);
} else {
define('HOST_TYPE', 'site');
define('SUBDOMAIN', FALSE);
}
}
in my config.php config:
switch (HOST_TYPE) {
case 'subdomain':
$config['base_url'] = 'http://'.SUBDOMAIN.'.hostname.com/';
break;
case 'localhost':
$config['base_url'] = 'http://localhost/devpage/';
break;
default:
//$config['base_url'] = 'http://mainpage.com/';
break;
}
in my database.php config:
...
$db['default']['hostname'] = 'localhost';
switch (HOST_TYPE) {
case 'subdomain':
$username;
$password;
$con=mysqli_connect("localhost","username_db","password_db","name_db");
$query = "SELECT * FROM subdomain_table WHERE subdomain_name = '".SUBDOMAIN."';" or die("Error in the consult.." . mysqli_error($con));
if ($result = mysqli_query($con, $query)) {
while($row = mysqli_fetch_array($result)) {
$username = $row["username"];
$password = $row["password"];
}
}else{
mysqli_close($con);
redirect('http://hostname.com'); //No sudomain found or error page
}
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
mysqli_close($con);
}else{
}
mysqli_close($con);
$db['default']['database'] = 'db_prefix'.SUBDOMAIN;
$db['default']['username'] = 'username_prefix'.$usuario;
$db['default']['password'] = $password;
break;
case 'localhost':
$db['default']['database'] = 'local_dev_db_name';
$db['default']['username'] = 'some_username';
$db['default']['password'] = 'some_password';
break;
default:
redirect('http://mainpage.com');
break;
}
$db['default']['dbdriver'] = 'mysql';
...
finally the constants.php config:
//this one resolve all your links!!!!!
switch (HOST_TYPE) {
case 'subdomain':
define('URL','http://'.SUBDOMAIN.'.hostname.com/');
break;
case 'localhost':
define('URL','http://localhost/devpage/');
break;
default:
define('URL','http://mainpage.com/');
break;
}
I hope you find it useful
I think the answer by #avenda goes someway but as you've mentioned there is only 1x DB then there is no need to play around with that code.
I think your simplest solution in your config file is simply:
$config['base_url'] = $_SERVER['HTTP_HOST'];
And then in your routes file:
if ($_SERVER['HTTP_HOST'] == 'x'){
$routes['default_controller'] = 'xController';
} elseif ($_SERVER['HTTP_HOST'] == 'y'){
$routes['default_controller'] = 'yController';
}
Haven't tested it but have a similar need coming up on a project so will have to implement something similar.

Codeigniter Session only writes userdata when sess_use_database is FALSE

I'm new to codeigniter and so when I set up my log in code I started out with simple and kept updating it to be more complex/secure. With that said I was making great progress creating a session and adding a user_data variable called "login_status" set to "1". To use as a reference for future page requests. Eventually I decided to go ahead and set up the database table ci_sessions and switch to that instead of just using a cookie. When I did this, all of the sudden my "login_status" variable was not being written anymore. As a result I could no longer access any subsequent pages and kept being redirected back to the log in screen.
In short, this exact same code works perfectly when I have sess_use_database set to false.
I'm not sure why this is happening but any help would be greatly appreciated!
Log in Controller:
class login extends CI_Controller
{
function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->helper('url');
$this->load->helper('form');
}
public function index($login = "")
{
$data = array();
if ($login == "failed")
$data['loginFailed'] = true;
else
$data['loginFailed'] = false;
$this->load->view('templates/headerAdmin');
$this->load->view('admin/loginform', $data);
$this->load->view('templates/footerAdmin');
}
public function assessme()
{
$username = $_POST['username'];
$password = md5($_POST['password']);
//checkme works fine and returns true
if ($this->checkme($username, $password))
{
$newdata = array( 'login_status' => '1' );
$this->session->set_userdata($newdata);
$this->mainpage();
}
else {$this->index("failed");}
}
public function checkme($username = "", $password = "")
{
if ($username != "" && $password != "")
{
$this->load->model('admin/loginmodel');
if ($this->loginmodel->validateCredentials($username, $password))
return true;
else
return false;
}
else
{
return false;
}
}
public function mainpage()
{
redirect('admin/dashboard');
}
The controller that I am redirected to after I can successfully log in:
class dashboard extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->helper('url');
}
public function index() {
//Make sure user is logged in
$login_status = $this->session->userdata('login_status');
//This is where I am redirected because the user_data is not being set
if(!isset($login_status) || $login_status != '1') {
redirect('admin/login');
}
$this->load->view('templates/headerAdmin');
$this->load->view('admin/dashboard/list');
$this->load->view('templates/footerAdmin');
}
}
Config:
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_expire_on_close'] = TRUE;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 300;
EDIT : Setting 'sess_match_useragent' to FALSE seems to prevent the session from being destroyed. Hopefully that will provide other clues as to what the cause of my problem is but obviously this, in itself, isn't an ideal solution
I had this problem and I fix it by this page
http://philsbury.co.uk/blog/code-igniter-sessions
This page say u should change Session library in \system\libraries
I Rename default Session file And create new Session file and put the code on it
its Worked

Resources