How to fix session being auto generated when page is reloaded/refresh using Codeigniter and Database as session driver? - codeigniter

I have my little project running perfectly on my local computer. However, when I run it into my laptop, an entry is automatically loaded in my ci_sessions table each time the page is being reloaded or refresh. I am using the database as my session driver.
Based on the screenshot: row 4 says that my login session store successfully. However, the 2 extra rows (5, 6) that are being added cause this code to fail:
public function isLoggedIn()
{
if($this->session->userdata('logged_in') === true) {
redirect('home', 'refresh');
}
}
public function isNotLoggedIn()
{
if($this->session->userdata('logged_in') !== true) {
redirect('login', 'refresh');
}
}
here's my config.php
$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
$config['cookie_prefix'] = '';
$config['cookie_domain'] = '';
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;
Here's my Page Controller
<?php
class Pages extends MY_Controller
{
public function view($page = 'login')
{
if (!file_exists(APPPATH.'views/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = ucfirst($page); // Capitalize the first letter
if($page == 'login') {
$this->isLoggedIn();
$this->load->view($page, $data);
}
else{
$this->isNotLoggedIn();
$this->load->view($page, $data);
}
}
}
MY_Controller Class
<?php
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('session');
}
public function isLoggedIn()
{
if($this->session->userdata('logged_in') === true) {
redirect('home', 'refresh');
}
}
public function isNotLoggedIn()
{
if($this->session->userdata('logged_in') !== true) {
redirect('login', 'refresh');
}
}
}
So far I have already tried adding the code below to my autoload.php but no luck.
$autoload['libraries'] = array('database', 'session');
Note: again this works in another unit with a similar setup.

after trying some work around, Codeigniter 3 is not yet compatible with php 7. I have to downgrade my php version to 5.6 to make it work. thanks folks for helping.

I suffered a lot of troubles with the original CI session library (included what you mention). Finally I arrived to this replacement that use native PHP session. It works!
Believe me, in the middle of a project, I did not stop to wonder why. Just works.
Here it is: CodeIgniter Native Session
BUT, due that it is an old library you MUST made some hacks. You can check those simple hacks in the library's forum
Just drop this file in codeigniter's library directory.

Related

codeigniter redirecting to a url

I have a website with a url like so (which works fine)
http://www.page.com/en/controller
But there always have to be a language and a controller in the url otherwise the page doesn't load or there is no language (no text).
Is it possible that when I enter a url like this
http://www.page.com
I get redirected to
http://www.page.com/en/controller
And the controller would be hidden? Only this would be left (my links require first segment to load a page with a particular language)
http://www.page.com/en
p.s tried routing and redirect, but with no luck
Sorry for the late response, I was away.
my routes
$route['default_controller'] = 'arena/display';
$route['(:any)/renginiai'] = "renginiai/getevents";
$route['(:any)/arena'] = "arena/display";
$route['(:any)/paslaugos'] = "paslaugos/displayServices";
$route['(:any)/kontaktai'] = "kontaktai/displayContacts";
$route['(:any)'] = 'pages/view/$1';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
My_Controller which is located in core folder. I load my language libraries from here.
/**
*
*/
class MY_Controller extends CI_Controller{
public function __construct()
{
parent::__construct();
$languages = array("lt", "en");
if(in_array($this->uri->segment(1), $languages)){
$this->lang->load($this->uri->segment(1), $this->uri->segment(1));
}
}
}
And this is my front page controller
<?php
class Arena extends MY_Controller{
public function display($year = NULL, $month = NULL){
/*$this->load->model('Mycal_model');*/
$this->load->model('Image_model');
$data['images'] = $this->Image_model->get_image_data();
$this->load->view('includes/head');
$this->load->view('includes/nav', $data);
$this->load->view('includes/header', $data);
//$this->load->view('includes/calendar', $data);
$this->load->view('includes/section');
$this->load->view('includes/footer');
}
}
open application/config/routes.php file and change
$route['default_controller'] = "en/controller";

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

Codeigniter session and redirect is not working in IE7 but working in IE8

I'm using codeigniter and have a simple user login setup. User submits their credentials, checks with the DB if they are valid, if they are the model passes the controller a session ID and is redirected to the user page. If the data is not correct the user is redirected to the login page with an error message. Nothing fancy here. The problems is it doesnt work in IE7. I'm not sure if its because of the redirect or the session creation. Works fine in all browsers except IE. I tested ie 8 with windows 7 on parallels and worked fine. The weird thing is that it doesnt work with on a pc with windows 7 IE7. Can someone tell me why the login page just keeps getting refreshed every time the user goes to login? I was told to try and add this code
$this->load->library('session');
$this->load->model('login_model');
$num_rows=$this->login_model->validate();
if($num_rows == 1)
{
$data = array(
'is_logged_in' => true,
);
$this->session->set_userdata($data);
redirect('admin/show_admin_home');
}
else
{
$data['message']="चुकीचे युझर नेम अथवा पास वर्ड";
$this->load->view('login',$data);
}
Login Model Code :-
<?php
class Login_model extends CI_Model {
function validate()
{
$username = $this->input->post('username');
$password = $this->input->post('inputPassword');
$this->db->select('*');
$this->db->where('login_username', $username);
$this->db->where('login_password', $password);
$query = $this->db->get('login');
return $query->num_rows;
}
}
?>
Add a site url in your redirect:
redirect(site_url('admin/show_admin_home'));
Change Config setting
$config['sess_cookie_name'] = 'cisession'; $config['sess_expiration'] = 84200; $config['sess_expire_on_close'] = FALSE; $config['sess_encrypt_cookie'] = FALSE; $config['sess_use_database'] = FALSE; $config['sess_table_name'] = 'cisessions'; $config['sess_match_ip'] = FALSE; $config['sess_match_useragent'] = FALSE; $config['sess_time_to_update'] = 300;

CodeIgniter server based 404

I've installed CodeIgniter on my localhost xampp server in the directory:
localhost/CI/
When I visit that directory directly I get to see the homepage but when I try to vist any other page I get a server based 404 page. I don't get the see the CI 404.
I already tried playing around with the uri_protocol but I can't get it to work. Any clue?
routes.php
$route['page/create'] = 'page/create';
$route['(:any)'] = 'page/view/$1';
$route['default_controller'] = 'page/view/hello-world';
$route['404_override'] = '';
Page controller
class Page extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('page_model');
}
public function view($slug)
{
$data['page'] = $this->page_model->get_page($slug);
if (empty($data['page']))
{
show_404();
}
$data['title'] = $data['page']['title'];
$this->load->view('templates/header', $data);
$this->load->view('page/view', $data);
$this->load->view('templates/footer');
}
public function create()
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Create a new page';
$this->form_validation->set_rules('title', 'Title', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('page/create');
$this->load->view('templates/footer');
}
else
{
$this->page_model->set_page();
$this->load->view('page/success');
}
}
}
The "Hello world!" shows nicely, but I can't get the create page to work. The view is located in views/page/create.php
xampp !!!! is the problem the mode rewite is not working fine wid it .. install apache as a standalone , add php and mysql and you can work fine any way it will cause other erros
$route['default_controller'] = 'page/view/hello-world';
change that to
$route['default_controller'] = 'page';
then move it to the top so you have
$route['default_controller'] = 'page';
$route['404_override'] = '';
$route['page/create'] = 'page/create';
$route['(:any)'] = 'pages/view/$1';
the order of things is inportant inside the routes.php
and inside page.php controler add a function index()

CodeIgniter CLI returns blank when utilizing a model. How to run cron securely?

I am trying to run a cron from the command line utilizing CodeIgniter.
Initially it was returning a blank but utilizing the Codeigniter forum I found there was a bug in version 2.1.3 which required a line edit in Input.php
That was fixed. Still it wasn't working, it was just loading my homepage.
More searching led me to change my uri_protocol to AUTO in my config, and finally the CLI was working with the example outlined on the CI website.
However when I have utilized a model in the cron controller, once again the CLI returns blank bangs head
The controller
<?php
class Cron extends CI_Controller
{
public function admin_update()
{
$this->load->model('admin_model');
$this->admin_model->admin_cron();
}
}
The model function
function admin_cron()
{
$this->load->database();
echo "two";
}
It seems to be the $this->load->database() line that is breaking it.. as in if i remove this it outputs 'two'..
Does anyone have any idea why?
Thanks
You are not providing any input for $this->load->database();
Instead it should be something like this
var $DB; //global variable
$this->DB = $this->load->database('database1',TRUE);
use $this->DB for running the db operations now like,
$this->DB->query($query);
Put these config enteries in the config/database.php
$db['database1']['hostname'] = 'serverIP';
$db['database1']['username'] = 'username';
$db['database1']['password'] = 'pwrd';
$db['database1']['database'] = 'DB name';
$db['database1']['dbdriver'] = 'mysql';
$db['database1']['dbprefix'] = '';
$db['database1']['pconnect'] = FALSE;
$db['database1']['db_debug'] = TRUE;
$db['database1']['cache_on'] = FALSE;
$db['database1']['cachedir'] = '';
$db['database1']['char_set'] = 'utf8';
$db['database1']['dbcollat'] = 'utf8_general_ci';
$db['database1']['swap_pre'] = '';
$db['database1']['autoinit'] = TRUE;
$db['database1']['stricton'] = FALSE;
PS: http://ellislab.com/codeigniter/user-guide/general/models.html#conn
above link is on how to connect to a database

Resources