how to get sessions for all functions at once in codeigniter? - php

I have created the session in login function. Now I want to use the created session on all other functions too if a user login then the created session should be applied to all other functions.
Thanks

I think you need to understand session first.
How do Sessions work?
Sessions will typically run globally with each page load, so the Session class should either be initialized in your controller constructors, or it can be auto-loaded by the system. For the most part the session class will run unattended in the background, so simply initializing the class will cause it to read, create, and update sessions when necessary.
To initialize the Session class manually in your controller constructor, use the $this->load->library() method:
$this->load->library('session');
Once loaded, the Sessions library object will be available using:
$this->session
Session data is simply an array associated with a particular session ID (cookie).
Visit CI Documentation of Session For More detail
See it live here: Session

In your login section
$this->db->where('email',$email);
$this->db->where('password',$pass);
$query = $this->db->get('admin');
$data= $query->result_array();
if($data){
$this->session->set_userdata('sessionVariable', $data);
redirect('controller_name');
}
Open autoload.php from application/config/autoload.php
$autoload['libraries'] = array('session');
OR
load session libraries in __construct() of your controller
public function __construct()
{
parent::__construct();
$this->load->library('session');
}
To get session data
$sessionData = $this->session->userdata('sessionVariable');

You can autoload the sessions in config.php
$autoload['libraries'] = array('database','Session','email');
OR
You can create a Base Controller in Core folder and extend all your other controller to that base controller.
Like this
<?php
class MY_Controller extends CI_Controller {
public $data = array();
function __construct() {
parent::__construct();
$this->data['errors'] = array();
$this->data['site_name'] = config_item('site_name');
$this->load->library('session');
}
}
Now All Your other Controller should be extended to your Base Controller instead of CI_Controller
In Your Controller
Controller 1:
class Login extends MY_Controller
{
function __construct() {
parent::__construct();
}
}
Controller 2:
class Dashboard extends MY_Controller
{
function __construct() {
parent::__construct();
}
}
So You will get just need to load your library is your base controller and get all the goodness of base controller in the child controllers. This will give you better hierarchy, code management and security

Related

Unable to locate the specified class: Session.php in Codeigniter

The browser:
Unable to locate the specified class: Session.php
This is my Controller:
<?php
class Chat extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Chat_model');
}
public function index() {
$this->view_data['chat_id'] = 1;
$this->view_data['student_id'] = $this->session->userdata('student_id');
$this->view_data['page_content'] = 'chat';
$this->load->view('chat');
}
public function ajax_addChatMessage() {
$chat_id = $this->input->post('chat_id');
$student_id = $this->input->post('student_id');
$bericht = $this->input->post('chat_id', TRUE);
$this->Chat_model->addChatMessage($chat_id, $student_id, $bericht);
}
}
When I put my model in comment in the parent::__construct(); // $this->load->model('Chat_model'); the error is gone.
This is my Chat_model:
<?php
class Chat_model extends CI_Controller {
public function Chat_model() {
parent::__construct();
}
public function addChatMessage($chat_id, $student_id, $bericht) {
$query = "INSERT INTO tbl_chatberichten (chat_id, student_id, bericht) VALUES (?,?,?)";
$this->db->query($query, array($chat_id, $student_id, $bericht));
}
}
class Chat_model extends CI_Controller
should be
class Chat_model extends CI_Model
If you use Codeigniter Modular Extensions HMVC this error can occur if you forget to change your class to extend MX_Controller instead of CI_Controller
So in your case you would start your class with:
class Chat extends MX_Controller {}
Instead of:
class Chat extends CI_Controller {}
I get the same error message when I involve the PDF library with the class name Pdf.php and load it via autoload as 'pdf'.
My mistake, the controller that will display my page I also named Pdf.php, and the error message appears ( that's the reason why I found this question :) ). The problem was immediately solved after I replaced the name of my controller with another name.
Add changes into your library configurations in application/config/autoload.php file
$autoload['libraries'] = array('database', 'session');
and in application/config/config.php set the encryption key(any key u like)
$config['encryption_key'] = 'thu23456789#[n,';
If you still get same error then copy
System/library/Session/Session.php to System/library/ folder, then it
should work
My solution:
Preface: If you don't use hooks, this will not be the solution for you.
I had this same issue, after upgrading to v3.0.6, and I definitely had everything setup correctly, as this is an existing site just being upgraded to v3+. My issue boiled down to hooks that I had loading 'pre-controller'. My hooks worked with v 2.0.X of CodeIgniter, but not with v3+.
If you are loading hooks before the session class is loaded, and your hook has a dependency on the session class, that may be your culprit. Try changing any pre-controller hooks to post-controller, or commenting them out completely to see if that fixes your issue. This is all located in application/config/hooks.php.
I encountered with same error. I attached "session" on --->
yourproject/application/config/autoload.php
$autoload['drivers'] = array("session");
Change your load library configuration in application/config/autoload.php file
$autoload['libraries'] = array('database', 'session');
In application/config/config.php set the encryption key(any key u like)
$config['encryption_key'] = 'thu23456789#[n,';
In my case the library name and controller class name was same i.e my controller class name was Ajaxer and also my library class name was Ajaxer. I changed my library class name to Ajaxer_lib and its resolved the issue.
In your Chat_model, try to change class Chat_model extends CI_Controller to class Chat_model extends CI_Model.
If none of the above solution worked, my workaround was:
In my autoload config, I had a library called 'auth'.
however, in my custom controller, somehow it was being messed up because 'auth' wasn't being auto-loaded(I've checked everything). Since I am only using it when logging in, I removed it from my autoload config and load it in my custom controller.
I never had this issue before but suddenly one day it happened.
Using [CodeIgniter v3]
Add this instead of your Chat controller constructor
public function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->model('Chat_model');
}
This loads the session library to your controller so that you can use the methods.
Model Extends CI_Model Not CI_Controller
class Chat_model extends CI_Model {
.............
}
Modify your library configurations in application/config/autoload.php file
$autoload['libraries'] = array('database','ci_session');
Set the encryption key for your applicatiion in application/config/config.php
$config['encryption_key'] = 'sdjfkdjkfj';
Copy system/libararies/Session/Session.php to application/libraries/
Rename application/libraries/Session.php to CI_Session.php
Now, CI_Session object will be available through below line
$this->ci_session

Can't autoload Tank Auth with the Codenigitier

I was able to implement the Tank Auth library with my website, but have an issue when I move the autoload of the library from the Auth controller to the codeignitier autoload library.
As you can see below I have commented out the auto load of the tank Auth library, if I load it here then everything works fine.
class Auth extends MY_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
//$this->load->library('form_validation');
$this->load->library('security');
// $this->load->library('tank_auth');
$this->lang->load('tank_auth');
}
THIS is now I load it in the codeignitier, as you can see pretty straight forward
$autoload['libraries'] = array('form_validation','email','upload','tank_auth');
this is the controller that I have defined
class MY_Controller extends CI_Controller
{
public $layout;
public function __construct()
{
//this sets where the header and footer file is loacated
parent::__construct();
$this->layout = 'layout/master';
}
}
The error I get when autoloading is The model name you are loading is the name of a resource that is already being used: users. Obviously it looks like its trying to create the object twice.
Why would autoloading before the Auth library cause this issue, when its auto loaded anyway in the Auth controller, maybe I'm missing some vital piece of understanding of codignitier.
thanks
Why don't you try renaming the library file? Besides, there is no harm in loading the library in the _construct.

Can I make an exception to codeigniter autoload?

My codeigniter site autoloads sessions. I have an XML API page that I created but I'm getting a session error because of that autoload. I would prefer not to load sessions on this controller but I don't want to have to load sessions manually on all of my other controllers. Can that be done?
Use a base controller to load the session class rather than autoload.php and have your controllers extend it. More information here: http://ellislab.com/codeigniter/user-guide/general/core_classes.html
// application/core/MY_Controller.php
class MY_Controller extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('session');
}
}
// you may add additional base controller classes here
You must extend this controller with the ones that you want to have access to the session class, so unfortunately you will have to make some edits to your existing controllers:
class UserController extends MY_Controller {
public function index()
{
// session class is loaded
}
}
Other controllers can continue to extend CI_Controller and the session class won't be loaded.
I use this method for all my CI projects and rarely use the autoloader.php, it allows much more flexibility.

What is the best way to apply mutiple time zone?

I am struggling to apply session basis time zone in Codeigniter(2.0).
Scenario:
Once user logged in the system I use the lat/lon to detect the time zone ID and set it to a session variable and then call set_timezone() into every controller's constructor.
Ex a helper file which is auto loaded:
function set_timezone($timeZoneId='')
{
if($timeZoneId!="")
{
date_default_timezone_set($timeZoneId);
mysql_query("SET SESSION time_zone = '".$timeZoneId."'");
}
}
My problem is I don't want to call set_timezone() in to every controller's constructor. What I want is to call globally instead of every controller's constructor.
You should create a parent controller called MY_Controller that all your other controllers extend. In the constructor of that class you can call set_timezone. With this solution the timezone will be set automatically in all child controllers.
Your MY_Controller should be stored in application/core and should look something like this:
class MY_Controller extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->set_timezone();
}
function set_timezone($timeZoneId='')
{
// Your code
}
}
Now all your other controllers should extend MY_Controller instead of CI_Controller. E.g.:
class WelcomeController extends MY_Controller
{
function __construct()
{
// This will call the constructor of MY_Controller,
// which in turn sets the timezone:
parent::__construct();
}
// Rest of your functions...
}
The another way is,
You can define it inside Library. You can create a library and define this function inside libraries and call it anywhere in the application. Don't forget to load the library in AutoLoad.
As Nikitas said create a library file like below and include the library file in autoload.phpb
class Timezoneconvert
{
function set_timezone($timeZoneId='') {
$this->obj =& get_instance();
$this->obj->load->database();
if($timeZoneId!="")
date_default_timezone_set($timeZoneId);
$this->obj->db->query("SET SESSION time_zone = '".$timeZoneId."'");
}
}
}
in autoload.php
$autoload['libraries'] = array('Timezoneconvert');
I have got a solution by using hooks.
1.enable the hooks in config
2.set it into hooks.php
class HookMyHandler {
function post_controller_constructor() {
$this->ci = & get_instance();
//my method name
}
}

Passing data to the view through the constructor method in Codeigniter

I am currently using the codeigniter tank_auth, at the start of every controller method I have to do the following:
$data['profile'] = $this->tank_auth->get_profile();
The main reason I do this is to display the current logged in username, and also get their privilege level.
I am going over the code trying to go by the DRY principle and have moved a lot of repeated code over to the _constructor method (Like checking if the user is logged in). I am just wondering if there is a way to move this code from the start of every method to the constructor.
My current constructor method looks like so:
public function __construct()
{
parent::__construct();
// If the user isn't logged in redirect to login page.
if (!$this->tank_auth->is_logged_in())
redirect('auth/login');
}
Thanks!
Add variable $data to the controller and use it for all your view data. For example:
public function __construct()
{
parent::__construct();
$this->data['profile'] = $this->tank_auth->get_profile();
}
When calling the view remember to call it like this:
$this->load->view('my_view', $this->data);
You can also extend CI_Controller with MY_Controller and put the login check in the constructor of MY_Controller. Just extend all controllers which need this check from MY_Controller instead of CI_Controller.

Categories