i made a simple logout url with the controller and it looks like this:
class Auth extends MX_Controller{
function logout(){
$this->session->sess_destroy();
$this->bootstrap->unsetUserCookie();
redirect(base_url(),'',301);
}
}
then
class Bootstrap{
function unsetUserCookie(){
$CI =& get_instance();
$CI->input->set_cookie(
array(
'name'=>'remember_me',
'value'=>'',
'expire'=>''
));
$CI->input->set_cookie(
array(
'name'=>'remember_me_n',
'value'=>'',
'expire'=>''
));
$CI->input->set_cookie(
array(
'name'=>'duser_lang',
'value'=>'',
'expire'=>''
));
$CI->input->set_cookie(
array(
'name'=>'duser_country',
'value'=>'',
'expire'=>''
));
}
}
i'm using the session DB these are the config params i'm using:
$config['sess_cookie_name'] = 'sess_id';
$config['sess_expiration'] = 0; //24hours -> 8640
$config['sess_expire_on_close'] = TRUE;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_session';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 3000000000;
then i created a simple session library and don't know if this can block anything but i guess no cause i receive no errors at all:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*We encode/decode all session data in base64 to avoid problems with multybityes data*/
class MY_Session extends CI_Session {
function set_userdata($data, $singleVar = NULL) {
if(is_array($data)){
$newValues = array();
foreach ($data as $key=>$value) {
$newValues[$key] = base64_encode($value);
}
parent::set_userdata($newValues);
}
else{
if(is_array($singleVar)){
$newValues = array();
foreach ($singleVar as $key=>$value) {
$newValues[$key] = base64_encode($value);
}
//Encode $singleVar
parent::set_userdata($data, $newValues);
}else{
parent::set_userdata($data, base64_encode($singleVar));
}
}
}
function set_flashdata($data, $singleVar = NULL) {
if(is_array($data)){
$newValues = array();
foreach ($data as $key=>$value) {
$newValues[$key] = base64_encode($value);
}
parent::set_flashdata($newValues);
}
else{
if(is_array($singleVar)){
$newValues = array();
foreach ($singleVar as $key=>$value) {
$newValues[$key] = base64_encode($value);
}
//Encode $singleVar
parent::set_flashdata($data, $newValues);
}else{
parent::set_flashdata($data, base64_encode($singleVar));
}
}
}
public function userdata($item) {
$data = parent::userdata($item);
if(is_array($data)){
$newData = array();
foreach ($data as $key => $value) {
$newData[$key] = base64_decode($value);
}
return $newData;
}else{
//Decode $data
return base64_decode($data);
}
}
}
/* End of file */
/* Location: ./application/controllers/ */
?>
the url is so simple,it just had to delete session and cookies, but the session and the cookies seems not to be deleted cause after launching the logout url i'm still logged.
Any clue please?
you code is fasle :
class Auth extends MX_Controller{
function logout(){
$this->session->sess_destroy();
$this->bootstrap->unsetUserCookie();
redirect(base_url(),'',301);
}
}
this extends is MY_Controller,
class Auth extends MY_Controller{
I had the same issue, it was the cache problem. It could be solved by adding the below header code inside the constuctor function or any other function where the login code is related.
header("Cache-Control: no-cache, must-revalidate");
Related
I try to check when someone logged in his/her account show the page with the session, I loaded session in libraries but the session doesn't work
And Sorry For My Bad English
Thanks For The Help :)
This Is The Model
class login_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
public function check()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$remember = $this->input->post('remember');
$this->db->select('username','password');
$this->db->from('user');
$this->db->where('username',$username);
$this->db->where('password',md5($password));
$result = $this->db->count_all_results();
if($result > 0)
{
$data_session = array(
'username'=>$username,
'islogin'=>true,
);
$this->session->set_userdata($data_session);
redirect('post/index');
}
This Is The Controller
class Post extends CI_Controller
{
public function index()
{
$login = $this->session->userdata('islogin');
if($login == true)
{
$data = array (
'name' => 'Hello',
);
$this->load->view('post/index',$data);
}
else {
redirect('login/index');
}
}
}
This Is The Config
$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'weblogdata';
$config['sess_expiration'] = 3600;
$config['sess_save_path'] = 'tbl_ci_sessions';
$config['sess_match_ip'] = TRUE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = TRUE;
$config['encryption_key'] = m.D~wt,wA:MjS9$]g<H4Z7eW.7`0vDbX$F`LUgCg+>$1?0L$vq1:7vaVf&d{U(
set your session condition on contruct(), change the controller to be like this :
function __construct() {
parent::__construct();
if($this->session->userdata('islogin') != true)
{
redirect('login/index');
}
}
function index() {
$data = array (
'name' => 'Hello',
);
$this->load->view('post/index',$data);
}
change your code to this
class Post extends CI_Controller
{
public function index()
{
$login = $this->session->userdata('islogin'); // $login will be 1
if($login)
{
$data = array (
'name' => 'Hello',
);
$this->load->view('post/index',$data);
}
else {
redirect('login/index');
}
}
}
How do I retrieve (and process) the params I have being passed in from this...
Modules::load('MembersList', $this->input->get(NULL, TRUE);
... into the module its being passed into?
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class MemberList extends MX_Controller {
function __construct()
{
parent::__construct();
$this->load->model('memberslist_model');
}
public function index()
{
// $params = how_do_i_retrieve it?
if ( ! isset($list) || $list == 'individuals')
{
$data['module'] = 'Individuals';
$data['results'] = $this->memberslist_model->list_individuals();
$data['count'] = count($data['results']);
$data['view'] = $this->load->view('list_individuals', $data, TRUE);
}
if ( $list == 'families')
{
$data['module'] = 'Families';
}
return $this->load->view('memberslist', $data, TRUE);
}
public function settings()
{
$data['settings'] = $this->memberslist_model->settings();
return $this->load->view('settings', $data, TRUE);
}
}
I understand that it is being passed as URI segments like codeigniter but I've tried everything and I can't get it to work.
I'm not sure which version you use, but you can try this:
$whatEver = Modules::run('MembersList/index', $this->input->get(NULL, TRUE));
class MemberList extends MX_Controller {
function __construct()
{
parent::__construct();
$this->load->model('memberslist_model');
}
public function index($params)
{
print_r($params);
// $params = how_do_i_retrieve it?
if ( ! isset($list) || $list == 'individuals')
{
$data['module'] = 'Individuals';
$data['results'] = $this->memberslist_model->list_individuals();
$data['count'] = count($data['results']);
$data['view'] = $this->load->view('list_individuals', $data, TRUE);
}
if ( $list == 'families')
{
$data['module'] = 'Families';
}
return $this->load->view('memberslist', $data, TRUE);
}
public function settings()
{
$data['settings'] = $this->memberslist_model->settings();
return $this->load->view('settings', $data, TRUE);
}
}
The method -- initially called in index.php -- redirects to another page. The problem here is that variable $logged_in isn't getting assigned a new value... which means that when the variable is used in the other page, it is read as false.
NOTE: The assignment of session 'id' and session 'type' is correct.
class Session {
public $logged_in = false;
public function login($data) {
if ($data) {
$_SESSION['id'] = $data['id'];
$_SESSION['type'] = $data['type'];
$this->logged_in = true;
}
}
}
This is a class and therefore is lost (its properties are lost) at the end of the first scripts execution and then recreated in the second in its initial state.
Classes do not live across executions of the same script or any other script.
If you wish to maintain the objects state, you will have to save the state to a file or maybe the real SESSION so you can re-hydrate the data when the second script starts
session_start();
class Session {
public function login($data) {
if ($data) {
$_SESSION['id'] = $data['id'];
$_SESSION['type'] = $data['type'];
$_SESSION['logged_in'] = true;
}
}
// getter function
public function is_logged_in()
{
// just in case check
if ( isset($_SESSION['logged_in']) ) {
return $_SESSION['logged_in'] == true;
} else {
return false;
}
}
}
Called like this
$s = new Session();
if ( ! $s->is_logged_in() ) {
header('Location: index.php');
exit;
}
To keep it away from the SESSION completely you could
class Session {
public $id;
public $type;
public $logged_in;
public function __construct()
{
if ( file_exists('my_session.txt')) {
$obj = json_decode(file_get_contents('my_session.txt'));
foreach($obj as $prop => $val) {
$this->{$prop} = $val;
}
}
}
public function __destruct()
{
file_put_contents('my_session.txt', json_encode($this));
}
public function login($data) {
if ($data) {
$this->id = $data['id'];
$this->type = $data['type'];
$this->logged_in = true;
}
}
}
$obj = new Session();
$obj->login(array('id'=>99, 'type'=>'TEST'));
print_r($obj);
$obj = null;
echo 'object nulled' . PHP_EOL;
print_r($obj);
echo ' NOTHING should be printed' . PHP_EOL;
echo 'object rehydrated' . PHP_EOL;
$obj = new Session();
print_r($obj);
create another method check_login() to re-assign the values in the new page and call it within __construct()
function __construct(){
$this->check_login();
}
public function check_login(){
if(isset($_SESSION['id']) && isset($_SESSION['type']){
$this->logged_in = true;
} else {
$this->logged_in = false;
}
}
For a small home project I am working on I have been looking for OO design patterns for Memcache implementation, but so far haven't found something I feel fits, so maybe my approach is wrong.
I have a DB connection class and an baseModel class so I want to implement caching on the baseModel where appropriate.
I have implemented the Database connection and the Cacher as Singlton patterns.
I cannot seem to get the Cacher class to read the data or trigger the echo "<p>Getting from cache"; line after I refresh the page on the base Model "loadFromDb" function
Here are the classes:
class Cacher {
protected static $cacher = null;
private static $settings;
public static function getCache() {
if (self::$cacher != null) {
return self::$cacher;
}
try {
self::$settings = parse_ini_file("./configs/main.ini");
self::$cacher = new Memcache();
self::$cacher->connect(
self::$settings['cache_server_host']
, self::$settings['cache_server_port']
);
} catch (Exception $e) {
// TODO log error and mitigate..
echo "Error connecting memcache";
die();
}
var_dump(self::$cacher->getstats());
return self::$cacher;
}
public static function getData($key) {
if (self::$cacher == null) {
self::getCache();
}
return self::$cacher->get($key);
}
public static function setData($key, $data, $expire = 0) {
if (self::$cacher == null) {
self::getCache();
}
if (self::$cacher)
return self::$cacher->set($key, $data, MEMCACHE_COMPRESSED, $expire);
}
}
class ModelBase {
protected $fields = array();
protected $class = null;
function __construct($class_name) {
$this->class = $class_name;
$this->fields = Database::getFields($class_name);
}
public function loadFromDB($id, $fromCache = true) {
$key = "loadFromDB_{$this->class}_{$id}";
if ($fromCache) {
$data = Cacher::getData($key);
if ($data) {
echo "<p>Getting from cache";
return unserialize($data);
} else {
echo "<p>No cache data. going to DB";
}
}
$values = Database::loadByID($this->class, $this->fields[0], $id);
foreach ($values as $key => $val) {
$this->$key = $val;
}
$dataSet = Cacher::setData($key, serialize($this));
echo "<p>Data set = $dataSet";
}
}
Memcache service is running and I can read data directly back if I read the cache directly after I write it, but what I want is to read the data from the DB only the first time the page loads, after that use the cache....
Any comments welcome...
Try doing it like (let the result of the cache decide if you should query the db):
<?php
public function loadFromDB($id) {
$key = "loadFromDB_{$this->class}_{$id}";
//query cache
$data = Cacher::getData($key);
//is it found
if (!empty($data)) {
//echo "<p>Getting from cache";
return unserialize($data);
}
//no so lest query db
else {
//echo "<p>No cache data. going to DB";
$values = Database::loadByID($this->class, $this->fields[0], $id);
foreach ($values as $key => $val) {
$this->$key = $val;
}
//store it in cache
//$dataSet = Cacher::setData($key, serialize($this));
$dataSet = Cacher::setData($key, serialize($values));//<<store the db result not the class
}
//echo "<p>Data set = $dataSet";
return unserialize($dataSet);
}
?>
I am working with Codeigniter 2.1.4 and also new to this framework. When ever i am trying to load the model on the controller class, error id 500 being thrown by the browser. Here is the code of the model class file name:
merchant_login.php
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
class Merchant_model extends MY_Model {
public $tbl_user = 'users';
function __construct(){
parent::__construct();
$this->load->database('merchant', TRUE, TRUE);
}
function user_login($data)
{
$this->db->from($this->tbl_user);
$this->db->where($data);
$query = $this->db->get();
if($query->num_rows()==1)
{
$this->db->select("CURRENT_LOGIN");
$this->db->from($this->tbl_user);
$this->db->where("USER_ID", $data["USER_ID"]);
$q = $this->db->get();
$res = $q->result();
$current_time = $res[0]->CURRENT_LOGIN;
$last_time = $current_time;
$current_time = date("Y-m-j H:i:s");
$arr = array(
"CURRENT_LOGIN" => $current_time,
"LAST_LOGIN" => $last_time,
"LAST_IP" => $this->input->ip_address()
);
$this->db->where("USER_ID", $data["USER_ID"]);
$this->db->update($this->tbl_user, $arr);
$this->db->from($this->tbl_user);
$this->db->where($data);
$query = $this->db->get();
return $query->row_array();
}
return false;
}
} ?>
Here is the code for controller and the file name is:
"login.php"
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Login extends MY_Controller {
function __construct() {
parent::__construct();
$this->load->library(array("form_validation", "session"));
}
//merchant section start
public function merchant_login() {
$this->session->keep_flashdata("return_url");
$this->form_validation->set_rules('loginName', 'Login', 'trim|valid_email|required');
$this->form_validation->set_rules('loginPassword', 'Password', 'trim|required');
if ($this->session->userdata("merchantLogged") != 1) {
if ($this->form_validation->run() == FALSE) {
$data["error"] = validation_errors();
header('Content-type: application/json');
echo json_encode($data);
} else {
$d['USER_ID'] = $this->input->post("loginName");
$d['USER_PASSWD'] = sha1($this->input->post("loginPassword"));
$this->load->model("merchant_model", "model", TRUE);
$user = $this->model->user_login($d);
if ($user) {
if ($this->input->post("security") == 'not') {
//Cal to a member function of the model class
if ($this->model->user_ip_check($d) == false) {
$this->session->set_userdata('u_id', $this->input->post("loginName"));
$this->session->set_userdata('u_pd', $this->input->post("loginPassword"));
$data['redirect'] = site_url("merchants/ip_security/");
} else {
$usr['type'] = "MR";
unset($user['USER_PASSWD']);
// unset($user['ID']);
unset($user['MM_NAME']);
//$this->load->database('default', TRUE, TRUE);
$this->session->set_userdata($usr);
$this->session->set_userdata($user);
$this->set_merchantLogged(1);
// if($this->session->flashdata("return_url")){
// $data['redirect'] = site_url("user/" . $this->session->flashdata("return_url"));
// }
// else{
$data['redirect'] = site_url("merchant/account");
// }
}
} else {
$d['que'] = $this->input->post("sec_q");
$d['ans'] = $this->input->post("sec_q_answer");
if ($this->model->check_que($d) == true) {
$this->session->unset_userdata('u_id');
$this->session->unset_userdata('u_pd');
$usr['type'] = "MR";
unset($user['USER_PASSWD']);
unset($user['MM_NAME']);
$this->session->set_userdata($usr);
$this->session->set_userdata($user);
$this->set_merchantLogged(1);
$data['redirect'] = site_url("merchant/account");
} else {
$data['redirect'] = site_url("merchants/ip_security");
}
}
} else {
$data["error"] = "Username or password are wrong";
$data["islogin"] = true;
}
header('Content-type: application/json');
echo json_encode($data);
}
} else {
if ($this->session->flashdata("return_url")) {
$data['redirect'] = site_url("merchant/" . $this->session->flashdata("return_url"));
} else {
$data['redirect'] = site_url("home");
}
header('Content-type: application/json');
echo json_encode($data);
}
}
}
?>
class Merchant_model extends MY_Model
replace
class Merchant_model extends CI_Model
class Login extends MY_Controller
replace
class Login extends CI_Controller
syntax error:$this->load->database('merchant', TRUE, TRUE); correct this one
My Suggestion please go through on the codeigniter document it can helpfull you
http://ellislab.com/codeigniter/user-guide/general/controllers.html
change your model file name from merchant_login.php to merchant_model.php
and change in login.php
$this->load->model("merchant_model", "model", TRUE);
to
$this->load->model("merchant_model", "", TRUE);