Hello I'm using inherited controllers. These are my controllers:
-baseAdminController:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class _BaseAdminController extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('session');
$calledFunction= $this->router->fetch_method();
if ($calledFunction!= 'loginView' && $calledFunction!= 'doLogin') {
$this->checkSession();
}
}
public function checkSession() {
if ($this->session->userdata('loggedIn') == false) {
$this->load->view('admin/loginView');
}
}
}
And my derived Admin Controllers:
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class AdminController extends _BaseAdminController {
public function indexView() {
$this->load->view('admin/indexView');
}
}
When i'm tring to login, CodeIgniter shows me both admin/loginView and admin/indexView. Because i'm checking session status at constructing my derived controller. How can i prevent to loading second view?
Thank in advance..
To answer your question, you could have done the following into your checkSession method:
public function checkSession() {
if ($this->session->userdata('loggedIn') == false) {
echo $this->load->view('admin/loginView', array(), TRUE);
exit;
}
}
Explanation: If you pass the third argument as TRUE, it will return the content of that file. Read ellislab.com for more info.
I hope this is related to your question:
I recently wanted to have a bunch of controllers extend a parent controller class (MY_Acl_Controller) that checked that the current logged-in user deserved access to each method (using a homegrown ACL library). The check was to be initiated in MY_Acl_Controller's constructor, so it would run on every request.
I wanted to set the Output class's output to the result of loading a view, then display the view and exit, but because this process was NOT executed in a routed controller method, I couldn't just call $this->load->view('errors/access_denied') and then return from the constructor function... CI would then carry on executing controller code.
So I created a MY_Output class, extending CI_Output, and added to it a public function display_with_exit():
public function display_with_exit()
{
$this->_display($this->final_output);
exit;
}
Then, in MY_Acl_Controller's constructor:
...
if(!$user_deserves_access)
{
$this->load->view('errors/access_denied');
$this->output->display_with_exit();
}
Maybe that might be useful to someone?
The advantage of this approach is that the Output class's _display() function sends all HTTP headers you'd like it to, as per any normal response.
Avoid exit; / function exit; or die; will terminate execution, its better practice in only debugging your code.
Try like below.
public function index(){
if($xx) return TRUE;
}
Related
I have 2 controllers, Listes.php and Campagnes.php. I want to use a method from the Listes controller in a method from the campagnes, is it possible? And is it possible to pass some parameters to it?
I use Codeigniter 3.
I tried some answers I found here but none of them worked.
I also this in the campagnes.php controller :
include_once (dirname(__FILE__) . "/Listes.php");
class Campagnes extends Listes {
public function listes_recap()
{
$result = parent::add($parameter1, $parameter2);
}
}
and in the Listes.php controller :
class Listes extends CI_Controller {
public function add($parameter1, $parameter2)
{
code here...
}
}
Thanks in advance for you're help.
There are a couple ways to achieve the results you want. But calling one controller from another is NOT the way to go. The "best" way to do it depends on what actually happens in the function that both controllers will use.
The first way is to create a "helper" that each controller will load and then use.
file: /application/helpers/list_add_helper.php
defined('BASEPATH') OR exit('No direct script access allowed');
if ( ! function_exists('add'))
{
function add($parameter1, $parameter2)
{
code here...
}
}
Use it in the controller like this
$this->load->helper('list_add');
$result = add($one, $two);
The second way is to create a custom library (class)
file: /application/libraries/List_adder.php
class List_adder
{
public function add($parameter1, $parameter2)
{
//code here
}
}
Used in any controller
$this->load->library('list_adder');
$result = $this->list_adder->add($one, $two);
If you need to use CI code in your custom library you have a little more work to do. Read all about it HERE.
calling one controller method from another controller is not a good programming strategy
I have a controller in CodeIgniter that does not respond to my requests. When I add a simple function to it function test1 {echo 'test';}, it returns blank response. When I add this function to another controller, it returns 'test' as expected. The syntax for the invalid controller does not differ from a valid one:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class authorized extends CI_Controller
{
function index(){echo "test";}
function __construct()
{
parent::__construct();
//Load Neccessary Models
$this->load->model('users');
$this->load->model('manufacturers');
$this->load->model('suppliers');
$this->load->model('administrators');
$this->load->model('banks');
//End Load Neccessary Models
define("AUTHORIZENET_API_LOGIN_ID", "");
define("AUTHORIZENET_TRANSACTION_KEY", "");
define("AUTHORIZENET_MD5_SETTING", "");
$this->load->library('authorizenet');
}
function test1(){echo "test";}
}
What can be the reason for its not responding?
Alright, got it to work by ensuring there is the following order of functions within the controller: function __construct(), then function index(), then my required function test1().
I'm new to codeigniter and I have two controllers: utility.phpand welcome.php.
In utility.php, I have functions:
function getdata() {
//code here
}
function logdata() {
//code here
}
Inside welcome.php, I have this function:
function showpage() {
//some code here
//call functions here
}
What I want to do is inside my welcome.php, I want to call the functions from utility.php. How do I do this? Thanks.
Refrence from here
To extend controller please either follow this tutorial or see some code below.
differences between private/public/protected
make a file in folder /application/core/ named MY_Controller.php
Within that file have some code like
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
protected $data = Array(); //protected variables goes here its declaration
function __construct() {
parent::__construct();
$this->output->enable_profiler(FALSE); // I keep this here so I dont have to manualy edit each controller to see profiler or not
$this->load->model('some_model'); //this can be also done in autoload...
//load helpers and everything here like form_helper etc
}
protected function protectedOne() {
}
public function publicOne() {
}
private function _privateOne() {
}
protected function render($view_file) {
$this->load->view('header_view');
if ($this->_is_admin()) $this->load->view('admin_menu_view');
$this->load->view($view_file . '_view', $this->data); //note all my view files are named <name>_view.php
$this->load->view('footer_view');
}
private function _isAdmin() {
return TRUE;
}
}
and now in any of yours existing controllers just edit 1st or 2nd line where
class <controller_name> extends MY_Controller {
and you are done
also note that all your variables that are meant to be used in view are in this variable (array) $this->data
example of some controller that is extended by MY_Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class About extends MY_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$this->data['today'] = date('Y-m-d'); //in view it will be $today;
$this->render('page/about_us'); //calling common function declared in MY_Controller
}
}
You don't is the short answer.
The point of MVC is to have your code well organized.
What you can do though is create a library in the libraries folder where you put methods you need in more than one controller.
For example you can make a mylog library, where you can put all your log related stuff. In any controller you will then call:
$this->load->library('mylog');
$this->mylog->logdata();
Besides functions that deal with data models should reside in models. You can call any model from any controller in CI
That is out of concept, if you want to call code in different controllers do following:
create helper and call function whenever (even in view) you want.
extend CI_Controller so you can use one or more functions in any controller that is extended.
Lets start with helper:
create file in folder application/helpers/summation_helper.php
use following sample of code
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
function sum($a, $b) {
//$CI =& get_instance();
// if you want to use $this variable you need to get instance of it so now instead of using $this->load... you may use $CI->load
$return = $a + $b;
return number_format($return, 3);
}
If you are going to use your helper in many controllers/views please load it in autoload, otherwise just load it manualy $this->load->helper('summation');
Extending Controller_CI: this is way better approach if you are using database. Please follow this tutorial, which explains it all.
*I have crafted an answer just before site went down posting this from cellphone.
I want to have class that checks login on all controllers that I specified.
Codeigniter version is 2.1.0 and I have php 5.3.10
Hier is how I would set it up:
I look at https://www.codeigniter.com/user_guide/general/core_classes.html
and I set it up like this:
in the /application/core/MY_Main.php
class MY_Main extends CI_Controller {
function __construct()
{
parent::__construct();
}
}
In my controller I have welcome.php
?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends MY_Main {
function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('welcome_message');
}
}
So if I place login check in MY-Main it should get work, but I cant get it work anyone???
I needed to add the following code to /application/config/config.php before I got the extenson of core classes working as described in the CI manual.
Code taken from here http://philsturgeon.co.uk/blog/2010/02/CodeIgniter-Base-Classes-Keeping-it-DRY
function __autoload($class)
{
if(strpos($class, 'CI_') !== 0)
{
#include_once( APPPATH . 'core/'. $class . EXT );
}
}
You logic is correct, that should work. It's exactly what I do on all my codeigniter sites. My code is a bit more complex as my login check is being called from a library (so I have to call $CI =& get_instance(); and then $CI in place of $this) but something like below should work for you. logged_in is just a name given to an item of session data set when the user logs in.
class MY_Main extends CI_Controller {
function __construct()
{
parent::__construct();
$session_data = $this->session->all_userdata();
if(!isset($session_data['logged_in']))
redirect('/login');
}
}
In regards to your comment above (http 500), not really sure what's going on there. The code you have pasted shouldnt be throwing errors like that so something else is probably going on. Try turning on codeigniters built in logging functionality.
http://codeigniter.com/user_guide/general/errors.html
You should create a library class and put it inside your library folder and load it as auto_load or inside your controllers.
create functions inside your library for example:
/**
*
* #return boolean check if a user is logged in or not
*/
function notLogin()
{
if (!$this->is_logged_in()){
//echo "pelase <a href='login'><b>login</b></a> to continue ";
redirect('home/login','refresh'); exit;
}
return true;
}
and call it inside your controller constructor or any functions you want like this:
class Main extends CI_Controller
{
private $POST = array();
private $ci_form;
function __construct()
{
parent::__construct();
//check if user is logged in or not
$this->m_auth->notLogin();
$this->load->library('form_validation');
$this->load->library('ajax_pagination');
}
}
It some time happens because of database connection.
Please check if your database :
has been selected by turning-on error reporting from your Cpanel error log.
user has been added to your database.
Hey! I'm very new to Codeigniter, I'm trying to protect the entire admin controller. I figured I'd start here:
function Admin()
{
parent::Controller();
if(!isset($_SESSION['loggedin'])){
$this->login();
}
}
but this is obviously incomplete. How do I also stop the method that is trying to run ( ie index() ), and am I on the right track here??
Thanks for your help!!
there is
Extend the base controllers:
MY_Controller.php
<?php
class MY_Controller extends Controller {
function __construct()
{
parent::Controller();
$user_id = $this->session->userdata('user_id');
$this->data['user'] = $this->user_lib->get($user_id);
}
}
?>
you can store all kinds of info in this construct. This just gets the currently logged in users ID and assigns it the $data['user'] . This will be adjusted depending on which sort of auth library you use but you get the gist. You now have access to the current users ID, and all their details, from within any controller that extends "MY_Controller"
now you can create an "admin" controller, or any number of other ones to restrict access. like so:
Admin_Controller.php
<?php
class Admin_Controller extends MY_Controller {
function __construct()
{
parent::Controller();
if($this->data['user']['group'] !== 'admin')
{
show_error('Error - you need to be an admin.');
}
}
}
?>
Public_controller.php
<?php
class Public_Controller extends MY_Controller {
function __construct()
{
parent::Controller();
if($this->data['user']['group'] !== 'member')
{
show_error('You need to login to see this page...');
}
}
}
?>
as you can see..possibilities are endless
So, for admin only pages - use the admin controller
for member only pages - public
for "normal" pages - use the default controller.
I'll link to Phil Sturgeon's article as it's where I read about it first
put the checking session code in every function in Admin Controller that you want to protect.
that is the easiest way to do it..