我有一个简单的代码,我把它放在我的控制器的构造函数
$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, no-transform, max-age=0, post-check=0, pre-check=0");
$this->output->set_header("Pragma: no-cache");
我使用这段代码是为了保证登出的安全。我的问题是,是否有办法把/声明我的代码为我的每个控制器的全局?因为很难对每个控制器的构造函数进行硬编码。
谢谢你的帮助
创建一个核心控制器可能是好的,但它将适用于应用程序中的每个控制器问题是,如果你有一个公共页面,你不想应用该设置。
我建议在你的Controllers文件夹中创建一个控制器,并以你喜欢的方式创建它。
的例子:
父管理控制器
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Admin extends CI_Controller {
public function __construct() {
parent::__construct();
$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, no-transform, max-age=0, post-check=0, pre-check=0");
$this->output->set_header("Pragma: no-cache");
}
}
从admin继承的控制器
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
include APPPATH.'controllers/admin.php';
class Dashboard extends Admin {
public function __construct() {
parent::__construct();
}
}
观察include APPPATH.'controllers/admin.php';
和class Dashboard extends Admin {
,您需要包含管理控制器,以便您可以扩展它。
我喜欢所有的答案,但最好的方法是使用钩子。首先把这个添加到hooks.php
$hook['display_override'] = array(
'class' => 'RouteProcess',
'function' => 'afterroute',
'filename' => 'RouteProcess.php',
'filepath' => 'hooks',
'params' => array()
);
然后进入hooks/文件夹,创建RoutesProcess.php创建如下文件:
class RouteProcess{
function afterroute(){
$this->CI =&get_instance();
$this->CI->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, no-transform, max-age=0, post-check=0, pre-check=0");
$this->CI->output->set_header("Pragma: no-cache");
echo $this->CI->output->get_output();
}
}
这样做的好处是它不需要调用控制器的__construct(),它可以被覆盖。
您可以使用CI钩子,并使用post_controller_constructor
钩子点调用钩子方法并在钩子中添加头。
集成详细信息可在用户指南点击这里
您可以通过核心目录
扩展默认的CI_Controllerapplication/core/MY_Controller.php中的: (MY_部分在你的config.php中定义)
class BaseController extends CI_Controller {
public function __construct() {
parent::__construct();
$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, no-transform, max-age=0, post-check=0, pre-check=0");
$this->output->set_header("Pragma: no-cache");
}
}
然后在控制器中使用:
class ControllerXYZ extends BaseController {
//your code
}
如果你的控制器不需要BaseController的功能,不要从BaseController扩展,而是从CI_Controller:
class ControllerXYZ extends CI_Controller {
//your code without the headers set
}
这也有一个优点,即每个控制器需要删除更多的代码,例如检查是否有人登录,您可以这样做:
class BaseController extends CI_Controller {
public function __construct() {
parent::__construct();
$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, no-transform, max-age=0, post-check=0, pre-check=0");
$this->output->set_header("Pragma: no-cache");
if(!$this->session->userdata('loggedIn') === True) {
redirect('/loginpage');
}
}
}