简体   繁体   English

如何在Codeigniter框架中拒绝访问控制器功能

[英]how to deny access to controller functions in codeigniter framework

how can i protect functions in my controller? 如何保护控制器中的功能?
Lets say a user is logged in, it can directly access any function just by typing in the url. 假设用户已登录,只需输入url就可以直接访问任何功能。

Some say use private function ..... 有人说使用私有功能.....
and Some say use underscore prefix to functions 有人说对功能使用下划线前缀

But there was no clear explanation how to do it and how it works. 但是,没有明确的解释如何做以及如何工作。

Hope you guys can make it clearer. 希望你们能说得更清楚。

Thanks everyone. 感谢大家。

According to the CI doc recommendations, and since checking whether or not a user is logged in is a common task which you'll likely want to perform in many of your controllers, you should first create a base controller class which has a method that checks whether a user is logged in. Something like this: 根据CI文档的建议,由于检查用户是否已登录是您可能要在许多控制器中执行的常见任务,因此您首先应创建一个具有检查方法的基本控制器类。用户是否已登录。类似以下内容:

class MY_Controller extends CI_Controller
{
  function __construct()
  {
    parent::__construct();
  }

  protected function _user_is_logged_in()
  {
     // logic which checks various conditions and returns a boolean
  }
}

Then you can use this controller when you are declaring the various other controllers for your site: 然后,当您为站点声明其他各种控制器时,可以使用此控制器:

class Welcome extends My_Controller
{
  public function index()
  {
     if(!$this->_user_is_logged_in()) 
     {
       // redirect, exit, show a 403, etc;
     }
  }

}

There is a feature of the CodeIgniter framework which will prevent underscore-prefixed methods from being used as page callbacks: CodeIgniter框架的一项功能可以防止将带下划线的方法用作页面回调:

http://ellislab.com/codeigniter/user-guide/general/controllers.html#private http://ellislab.com/codeigniter/user-guide/general/controllers.html#private

And defining these methods as private or protected when you declare them will obviously affect their scope, definition and extension respectively. 并且在声明它们时将这些方法定义为privateprotected方法显然会分别影响它们的范围,定义和扩展。

You can create private functions in your controller by using the underscore prefix. 您可以使用下划线前缀在控制器中创建私有功能。

http://ellislab.com/codeigniter/user-guide/general/controllers.html#private http://ellislab.com/codeigniter/user-guide/general/controllers.html#private

In some cases you may want certain functions hidden from public access. 在某些情况下,您可能希望某些功能对公共访问隐藏。 To make a function private, simply add an underscore as the name prefix and it will not be served via a URL request. 要将函数设为私有,只需添加下划线作为名称前缀即可,并且不会通过URL请求提供。 For example, if you were to have a function like this: 例如,如果要具有以下功能:

private function _utility()
{
  // some code
}

Trying to access it via the URL, like this, will not work: 像这样尝试通过URL访问它不起作用:

example.com/index.php/blog/_utility/ example.com/index.php/blog/_utility/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM