CodeIgniter session available in one controller but not in other...
Session is setting user controller
class User extends CI_Controller {
// SEssion worked here
public function __construct()
{
parent::__construct();
session_start();
}
function setSess (){
// database model call, Value comes from database
$_SESSION['user'] = array ( 'isLoggedIn' => true,
'id' => $userData[0]['id'],
'username' => 'ABC',
'email_address' => $userData[0]['email_address'],
'country' => $userData[0]['country'],
'lastLoggedin' => $lastLoginTime
);
// Redirect to profile
}
}
Unable to receive it in
class Profile extends CI_Controller {
public function __construct()
{
parent::__construct();
session_start();
}
public function index() {}
public function display() {
ECHO "<PRE>";
print_r($_SESSION);
$data['title'] = 'Profile of '.$_SESSION['user']['username'];
// Gives error here while echoing $_SESSION['user']['username']
}
}
What am i missing here? Any suggestion?
Do not use session_start(), instead, load CodeIgniter session library
In User Controller:
class User extends CI_Controller {
public function __construct()
{
parent::__construct();
if(!isset($this->session)) {
$this->load->library('session'); # do not use 'session_start();'
}
}
function setSess (){
$_SESSION['user'] = array ( 'isLoggedIn' => true,
'id' => $userData[0]['id'],
'username' => 'ABC',
'email_address' => $userData[0]['email_address'],
'country' => $userData[0]['country'],
'lastLoggedin' => $lastLoginTime
);
}
...
}
In Profile Controller:
class Profile extends CI_Controller {
public function __construct()
{
parent::__construct();
if(!isset($this->session)) {
$this->load->library('session');
}
}
...
}
Also make sure your config file is setup correctly. Follow documentation here CodeIgniter Sessions
Related
I use smarty and ci 3.0.6 can I use a base controller in my core? I do it but I don't have any value in my view
controller:
class MY_Controller extends CI_Controller {
public $stats;
public $title;
public function __construct() {
parent::__construct();
$this->load->model('User_Model');
$var->stats = $this->User_Model->count_Unverified_adviser();
$t=$var->stats->Unverified;
$var->title = 'title';
$this->custom_smarty->assign('vars',$var);
$this->load->vars($var);
} }
my controller that load view:
class Adviser extends MY_Controller {
function __construct()
{
parent::__construct();
$this->load->model('User_Model');
}
public function index()
{
$this->custom_smarty->assign('url',base_url());
$this->custom_smarty->display('test.tpl');
}
my test.tpl:
<td>{$vars.title}</td>
You are giving an object to the assign function.
To access $vars.title in this way you should give an array:
$this->custom_smarty->assign('vars', array( 'title' => 'somevalue' ));
I have this login function in controller :
public function members() {
if($this->session->userdata('is_logged_in')){
redirect('pag/index');
}else{
redirect('main/restricted');
}
My index will load, but my model/controllers functions won't load because of the user session.
I read about doing a MY_controller in the core, mine looks like this :
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
require(APPPATH.'/libraries/HttpResponse.php');
class MY_Controller extends CI_Controller {
private $_additional_css = array();
private $_additional_js = array();
function __construct() {
parent::__construct();
}
public function is_logged_in($user=true)
{
$user = $this->session->userdata('user_data');
return isset($user);
}
}
But it wont work, any idea?
make changes in login controller function :-
pass exact session parameter that you set in your session
public function is_logged_in('user_data')
{
$user = $this->session->userdata('user_data');
return $user;
}
after this make changes in MY_conroller:- pass variable parameter in is_logged_in function
public function is_logged_in($user_data)
{
$user = $this->session->userdata($user_data);
return $user;
}
Enable hook in config.php
$config['enable_hooks'] = TRUE;
write following code into application/config/hooks.php file
$hook['post_controller'] = array(
'class' => 'MyClass',
'function' => 'Myfunction',
'filename' => 'Myclass.php',
'filepath' => 'controller',
'params' => ''
);
and last step is Create myclass.php controller in your controller folder
class myclass extends CI_Controller
{
function myfunction()
{
if($this->session->userdata('is_logged_in'))
{
redirect('pag/index');
}
else
{
redirect('main/restricted');
}
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
echo user in view from sessions code igniter
I don't want to define and store the user in every controller and then pass it to the view.
Here's my controller:
Login controller:
class LoginController extends CI_Controller {
function index(){
$new['main_content'] = 'loginView';
$this->load->view('loginTemplate/template', $new);
}
function verifyUser(){
//getting parameters from view
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$this->load->model('loginModel');
$query = $this->loginModel->validate($data);
if ($query){
//if the user c validated data variable is created becx we want to put username in session
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('sessionController/dashboard_area');
}else{
$this->index();
}
}
function logout()
{
$this->session->sess_destroy();
$this->index();
}
}
?>
My controller, which I've stored in core folder, so now every controller now extends this controller. I think this controller can be customize so I can access the user in every view page which extended this controller:
class MY_Controller extends CI_Controller{
function __construct(){
parent::__construct();
$this->is_logged_in();
}
function dashboard_area(){
$data['main_content'] = 'dashboardView';
$this->load->view('dashboardTemplate/template', $data);
}
function is_logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if(!isset($is_logged_in) || $is_logged_in != true)
{
echo 'You don\'t have permission to access this page.';
redirect('loginController');
}
}
}
?>
Here is my simple one member controller which extended the above controller:
Here in index function I am storing the username and then pass into the view which I don't want to do:
class CategoryController extends MY_Controller {
function index(){
$data['main_content'] = 'categoryView';
$username= $this->session->userdata('username');
$data['username']=$username;
$this->load->view('dashboardTemplate/template',$data);
}
You can just call $this->session->userdata('username') in your view.
It is stored in the session, so you do not have to pass it to the views from the controller.
UPDATE PER COMMENT;
if you want to load a view depending on the base controller (eg user), I would use a template library and set the template to use in the construct of the base controller.
For example (using this template library);
class MY_User extends CI_Controller {
public __construct() {
parent::__construct();
$this->is_logged_in();
$this->template->set_template('user');
}
}
class MY_Admin extends CI_Controller {
public __construct() {
parent::__construct();
$this->is_logged_in();
$this->template->set_template('admin');
}
}
I am new to codeigniter. I am trying to insert datat to mysql database to a table named class_record. My controller add_record.php coding as below :
class Add_record extends CI_Controller
{
function __construct()
{
parent::__construct();
}
function index()
{
$this->load->model('add_record_model');
}
}
And my model add_record_model is as below :
class add_record_model extends CI_Model{
function __construct(){
parent::__construct();
}
function index(){
$data = array(
'roll_number' => 15,
'student_name' => 'Dhrubajyoti Baishya',
'branch_code' => 'CS'
);
$this->db->insert('class_record',$data);
}
}
But when I type http://localhost/codeigniter/index.php/add_record in url data are not inserted to the database. What is the problem ?
You're not actually doing anything in the controller and models don't have index functions the way you're thinking.
You want something like this:
class Add_record extends CI_Controller
{
function __construct()
{
parent::__construct();
}
function index()
{
$this->load->model('add_record_model');
$this->add_record_model->insertRecords();
}
}
class add_record_model extends CI_Model{
function __construct(){
parent::__construct();
}
function insertRecords(){
$data = array(
'roll_number' => 15,
'student_name' => 'Dhrubajyoti Baishya',
'branch_code' => 'CS'
);
$this->db->insert('class_record',$data);
}
}
The controller does what it says it controls things. By loading the model all you are doing is exposing the models functions to the controller to use directly. Honestly you would pass the data to the model from the controller as well, the function you have is a good little test function but does nada really. How you really want to be doing it is something along these lines.
class Add_record extends CI_Controller
{
function __construct()
{
parent::__construct();
}
function index()
{
$data = array(
'roll_number' => 15,
'student_name' => 'Dhrubajyoti Baishya',
'branch_code' => 'CS'
);
$this->load->model('add_record_model');
$this->add_record_model->insertRecords($data);
}
}
class add_record_model extends CI_Model{
function __construct(){
parent::__construct();
}
function insertRecords($data){
$this->db->insert('class_record',$data);
}
}
I am creating one login authentication app in CakePHP
and getting this Fatal error: Call to a member function allow() on a non-object in /var/www/cakephp1/app/Controller/users_controller.php on line 5
and this is my controller code
users_controller.php
<?php
class UsersController extends AppController {
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add');
}
public function add() {
if (!empty($this->data)) {
$this->User->create();
if ($this->User->save($this->data)) {
$this->Session->setFlash('User created!');
$this->redirect(array('action'=>'login'));
} else {
$this->Session->setFlash('Please correct the errors');
}
}
$this->set('groups', $this->User->Group->find('list'));
}
public function login() {
}
public function logout() {
$this->redirect($this->Auth->logout());
}
public function dashboard() {
$groupName = $this->User->Group->field('name',
array('Group.id'=>$this->Auth->user('group_id'))
);
$this->redirect(array('action'=>strtolower($groupName)));
}
public function user() {
}
public function administrator() {
}
public function manager() {
}
}
?>
app_controller.php
<?php
class AppController extends Controller {
public $components = array(
'Acl',
'Auth' => array(
'authorize' => 'actions',
'loginRedirect' => array(
'admin' => false,
'controller' => 'users',
'action' => 'dashboard'
)
),
'Session'
);
}
?>
View login.ctp
<?php
echo $this->Form->create(array('action'=>'login'));
echo $this->Form->inputs(array(
'legend' => 'Login',
'username',
'password',
'remember' => array('type' => 'checkbox', 'label' => 'Remember me')
));
echo $this->Form->end('Login');
?>
I am using CakePHP version 1.3
1.Solution: All what you need to do is to add this line in your UsersController:
public $components = array('Auth');
Or
2.Soluton: In UsersController:
App::uses('AppController', 'Controller');
class UsersController extends AppController {
}
and then in AppController:
public $components = array('Auth');
There are two common causes for this type of error:
The App controller file is not being loaded
If the AppController class doesn't exist - Cake will use a fallback for it taken from the core - it's just an empty class. For the error in the question to occur - the Auth component hasn't been loaded, the most likely reason for that is that the file app/app_controller.php either doesn't exist or a different AppController class file was loaded before looking for it.
This can be confirmed using get_included_files, e.g.:
class UsersController extends AppController {
public function beforeFilter() {
if (!isset($$this->Auth)) {
debug(get_included_files());
die;
}
Look for which app_controller.php file has been loaded - if it's not the file containing the class in the question, that's the problem.
Overridden constructor, not calling parent
Good children always call their parents :)
If the constructor (or any method) is overridden and does not call the parent function, then e.g. the components property won't get merged/set correctly or component classes won't be initialised.
If the right app_controller.php file is being loaded focus on the methods defined within the controller classes and check they are calling parent::methodname (for the users controller, and the app controller). Specifically verify that the Controller::__construct is being called since that's where most of the class initialization logic is in 1.3.
The error sounds like the loading of the Auth-component failed. Have you tried removing the settings from the $components array and see if the error persists?