Where to set session in Codeigniter? - php

I'm reading the Codeigniter 2.2 tutorial and I am not clear on how to use sessions for logging in.
Say I have a login.php, which checks user data with the database. Then if its ok then I should set the session in a controller?
$this->load->library('session');
And then in say admin.php page I should check if session exists by? :
$this->session->user_data('item'); ??
Or how do I check if the person is logged in?
Thank you

Based on the docs, to do anything custom within session you need to load the session library. If you plan to use session throughout your application, I would recommend autoloading the library. You do this from within config/autoload.php.
$autoload['libraries'] = array('session');
Then you won't have to use $this->load->library('session'); on every page.
After the library is loaded, set your custom information, maybe based off some information from your database. So in your case, this would be in login.php:
$this->session->set_userdata('userId', 'myId'); where userId would be the name of the session variable, and myId would be the value.
Then, on subsequent pages (admin.php), you could check that the value is there.
if($this->session->userdata('userId') == '') { //take them back to signin }

To set user session
$the_session = array("key1" => "value1", "key2" => "value2");
$this -> session -> set_userdata($the_session);
To read user session
$foo = $this -> session -> userdata('key1');
You need $this->load->library('session'); every time prior you use CI session functions. Or you can set it up in autoload.php $autoload['libraries'] = array('session');

load session library
$this->load->library('session');
set session
$_SESSION['email'] = $data['email'];
unset session
$this->session->unset_userdata($_SESSION['email']); // $this->session->sess_destroy();

$this->load->library('session');
$this->session->userdata("email")

Related

Unable retrieve session value in view in codeigniter

I have session variable on gear.php view as
$_SESSION['dbRecords'] = $product_number;
but when I go to different view eg. order.php, I am unable to retrieve value using
$product_number = $_SESSION['dbRecords'];
order.php loads on submit.
I am using CodeIgniter 3.
How can I get the value of $_SESSION['dbRecords']?
You should get session data via Codeigniter style
setting data to session
$this->session->set_userdata('dbRecords', $product_number);
and get data from sessio
$dbRecord = $this->session->userdata('dbRecords');
I am not sure, the way you are doing is OK.
i think you are not loaded session library
add session library in autoload
application/config/autoload.php
$autoload['libraries'] = array('session');
OR
load in controller __contruct() function
$this->load->library('session');

codeigniter login and user session

I built an user login to my site by this guide:
http://www.iluv2code.com/login-with-codeigniter-php.html
I have few question about session's
I need to put the session_start(); in every controller or there is a way in codeigniter that it will automaticlly be in all controllers? (should I do that?)
and there is a other way rether to put in every function that:
if($this->session->userdata('logged_in'))
{
//function code
}else{
//If no session, redirect to login page
redirect('../login', 'refresh');
}
or should I do that for every controller function (for example if I have controller named page and he have the functions :index,edit,view I need to put it for every one of them?
and last question, I have logout button on the top of every page called by view/header
should I also put this function:
function logout()
{
$this->session->unset_userdata('logged_in');
session_destroy();
redirect('home', 'refresh');
}
in every controller or I can do it a "golbel" function in some way?
EDIT:
I use this in hooks.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| Hooks
| -------------------------------------------------------------------------
| This file lets you define "hooks" to extend CI without hacking the core
| files. Please see the user guide for info:
|
| http://codeigniter.com/user_guide/general/hooks.html
|
*/
$hook['post_controller_constructor'] = array(
'class' => 'SessionData',
'function' => 'initializeData',
'filename' => 'loginHelper.php',
'filepath' => 'hooks',
'params' => array()
);
and this in loginHelper.php:
<?
class SessionData {
var $CI;
function __construct(){
$this->CI =& get_instance();
if(!isset($this->CI->session)) //Check if session lib is loaded or not
$this->CI->load->library('session'); //If not loaded, then load it here
}
function initializeData() {
// This function will run after the constructor for the controller is ran
// Set any initial values here
if(!$this->CI->session->userdata('logged_in')){ //call session methods with super object
redirect('../login', 'refresh');
}else{
$data['user'] = $this->CI->session->userdata('logged_in');
}
}
}
?>
/* End of file hooks.php */
/* Location: ./application/config/hooks.php */
the user['data'] not created in all the pages. where am I wrong?
For your second question about logout, I usually put the logout function in a User controller and call it as Log Out.
For your first question, I saw a tutorial how you do user login in a controller and extend that controller in your regular controller, thats how you avoid login check in every function. I am trying to find that tutorial, once I get it, I'll share it, but the concept is like that way.
you do not need to put the session_start(); in every controller!
You could simply start the session class in the autoload.php file in your config directory!
$autoload['libraries'] = array('database', 'session', 'encrypt');
Also, it is better to check if the user is logged in, inside the constructor function of the classes!
if(!$this->session->userdata('logged_in'))
redirect('loginController/loginFunction', 'refresh');
and to destroy all the sessions when logging out, you could use sess_destroy();
Initializing a Session
To autoload Session, open the application/config/autoload.php file and add the item you want loaded to the autoload array so: $autoload['libraries'] = array('session'); Yo don't use session_start(); and session_destroy(); at all.
Session Documentation:
https://ellislab.com/codeigniter/user-guide/libraries/sessions.html
Auto-loading Resources:
https://ellislab.com/codeigniter/user-guide/general/autoloader.html
To Check Login
Use Hooks to avoid chunky code dupplications and it is better practise. Navigate bottom of the page and read Hook Points so you get an idea. It is easy! Definitely learn hooks.
Logout
You answer explained here.
After alot of working I solved the problem with the login check.
I didn't use the hooks. I build a MY_Controller in core folder and exteds it in all my controllers expect from the login controller.
In the MY_Controller I use thie login check.
CodeIgniter core controllers:
https://philsturgeon.uk/blog/2010/02/CodeIgniter-Base-Classes-Keeping-it-DRY/

Passing data between two controllers MVC

I am using CodeIgniter and I have two different controllers - login.php and site.php
In login.php
function credentials(){
$user = $this->input->post('username');
// there is some code here
}
In site.php, I have function members_area() I need to pass the variable $user from login.php to site.php. How do I do this ?
Thanks
If you are talking about user logins here.. In your Login controller you verify user credentials. If so then you need to set a session variable
$this->sessions->set_userdata('user_id',$user_id);
redirect('site/members_area');
Then in your Site controller you retrieve the data for that user from DB.
$current_user = $this->sessions->userdata('user_id');
And you get your required data from DB.
just take a redirect to site/members_area/$user
and you'll get $user parameter in the function members_area($user)
Turns out that a controller is used to control what is sent to a view. If the design is right you're not really supposed to send data between two controllers.
I sent inserted the value of username into a session.
So, In login.php
$this->session->set_userdata($data);
and retrieved the value in site.php
$data['userid'] = $this->session->userdata('username');
$this->load->view('members_area' , $data); //send the info to the controller
if you want some common functions in two controller put it in a helper file
http://ellislab.com/forums/viewthread/55212/

CodeIgniter Session variables not passing

I am using native PHP sessions ($_SESSION) with CodeIgniter framework.
I have a "Login" controller loads view where user enters login and password.
After the user submits the login form, the "Login" controllers authenticate() method is called.
If everything is alright i add some data to $_SESSION array, then i redirect user to "Organisation" controllers myOrganisation() method.
I'm calling session_start() in Login/login() , Login/authenticate() and Organisation/myOrganisation() methods, but still the session is not passed, because in myOrganisation() method the session is new.
I tested my cookies functionality with creating 2 test php pages, where i just echo session id. It works perfectly.
Maybe i am not putting session_start() in all places it needs to be? (i put them in all controllers methods).
Login Controller:
class Login extends CI_Controller {
public function index() {
session_start();
$this->load->view("Login/index", $data);
public function authenticate() {
session_start();
$_SESSION['login'] = $login; // everything is alright, redirect
header("location: ".base_url()."Organisations/MyOrganisation");
Organisation controller:
public function MyOrganisation() {
session_start(); // here session is a new one, not passed
if(isset($_SESSION['login'])) {
I don't know what was wrong with the session_start() placements that i did, but the one thing that solved the problem was to place it in index.php in main folder
session_start() can also be specified in a constructor, not every method in a class. That means both your controllers can have this:
function __construct () {
ini_set("session.gc_maxlifetime", 14400);
ini_set("session.cookie_domain", .yourdomain.com);
session_set_cookie_params(14400, '/', .yourdomain.com);
session_start();
}
The first 3 lines in a constructor are to make sure the session cookie is valid for a long time and under you domain.
Besides that (and not closed index() and authenticate() methods), where's $login coming from?

Remember the session with Auth module?

I'm trying to make the Auth module to 'remember' the user session with a checkbox on the login page. What happens is that no cookie is created, only session as usually. I've noticed the user_tokens table, but don't see any use of user_token model's methods at all. I do pass (bool) TRUE as a third parameter to login() method, but there's no difference.
Is this feature complete at all or I have to add my own by overwritting the login() method of Model_Auth_User ?
What's the best practice for this ?
I also opened a topic on Kohana Forums
Answer from the Kohana forum (credit to biakavero) pasted here for reference:
Call Auth::instance()->login() with $remember = TRUE
DB Token for current user created. Cookie authautologin generated.
Destroy user object : Session::instance()->delete('auth_user'); // dont call logout() method as it will delete cookie & token
Call Auth::instance()->auto_login() and check for Auth::instance()->get_user() // should return Model_User object

Categories