Global function for protected pages |
[eluser]Jagar[/eluser]
Greetings! I want to make a function global (CheckAdmin), so that if a user tries to access the admin pages and their are not logged in, they'll be redirected back to the login page. Could anyone please help me accomplishing this, or where to have this function so it's accessible in all pages. Thanks
[eluser]Dam1an[/eluser]
To make a function accessible in all your pages, create a helper for it, and autoload it. That function woud then return a boolean (true or false) so you can do Code: if(is_admin()) { I'm assuming you have a session var if the user is an admin, so the helper function would look something like Code: function is_admin() {
[eluser]Jagar[/eluser]
Dam1an thanks for the quick reply. Now for the helper, do I have to load the session library anywhere? Like inside the helper or within the controller. Thanks
[eluser]t'mo[/eluser]
Another take on this: Suppose all your "admin" functions are in a single controller (and that any non-admin functions are *not* in that same controller). Then you could simply make that controller's constructor check for you. E.g., Code: class AdminController extends Controller The main advantage to this style of admin checking is you avoid multiple calls to the "is_admin" function.
[eluser]xwero[/eluser]
A third way is to create a post_controller_constructor hook where you call the CheckAdmin function.
[eluser]Dam1an[/eluser]
[quote author="Jagar" date="1240794665"]Dam1an thanks for the quick reply. Now for the helper, do I have to load the session library anywhere? Like inside the helper or within the controller. Thanks[/quote] Sorry, I'm so used to having session autoloaded, I forgot to mention that
[eluser]kirkaracha[/eluser]
I'm having trouble getting this to work. Here's my helper: Code: <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); I'm autoloading both the authentication helper and the session library. I get this error in my controller: "Fatal error: Call to undefined method About::_authenticate_admin() in /codeigniter/application/controllers/about.php on line 18." The controller calls _authenticate_admin like this: $this->_authenticate_admin(); I also get "Undefined variable: is_admin" if I try to use is_admin in a view.
[eluser]Unknown[/eluser]
@kirkaracha You probably figured it out by now, but your helper should be in a class. Not just 2 functions. Start it like: Code: Class Adminhelper |
Welcome Guest, Not a member yet? Register Sign In |