我需要解决一个疑问,我留下细节。
我有一个类有多个与用户数据相关的数据库查询,要访问这些方法需要验证用户是否已登录,我使用 php 初始化程序“__construct ()”方法执行此操作,如果用户登录。
<?php
class User()
{
public function __construct() {
if ( !isset($_SESSION['user']) ) {
$data = array(
'response' => false,
'message' => 'You must login to access this page'.
);
echo json_encode($data);
}
}
public function index() {
// The user can access if you are logged
}
public function edit_profile() {
// The user can not access if you have not logged
}
public function save_profile_data() {
// The user can not access if you have not logged
}
}
?>
我的问题:
- 使用__construct()是资源密集型的最佳最优选择吗?
- __construct()使用安全,防止用户访问其他未指定是否有编码 session 变量的方法。
即如果用户调用了edit_profile()方法,而这个方法没有检查session的代码,但是我在__construct()中指定了>, 用户可以访问这个方法吗?
我希望你能帮助我,我将不胜感激。
最佳答案
我建议您在库文件夹中创建自己的库文件 这是类文件
class Authenticate {
var $table;
public function __construct()
{
$this->ci =& get_instance();
}
public function is_logged_in()
{
$sessionid = $this->ci->session->userdata('moderId');
if($sessionid)
{
return isset($sessionid);
}
else if(!$sessionid) {
redirect(base_url() . 'moderator');
}
}
}
在你的 Controller 中,使用这个函数。如果你把这个函数放在 Controller 的构造函数中,那么它将对所有方法可用 Controller
class B2bcategory extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('moderator/b2bcategory_model');
$this->authenticate->is_logged_in();
}
}
关于PHP - 使用 __construct() 检查是否有 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35215727/