Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter global function

Where can I place my "global" function, which will check, if user is logged in?

Because I want to do something like: user is able to browse some pages only when the function isLogged() returns TRUE, and I'd have to use it in some views, that's why it should be a "global" function, which I can access from anywhere.

Is that possible? Or there is any better solution for this?

like image 471
Cyclone Avatar asked Feb 11 '12 01:02

Cyclone


People also ask

How to declare global in PHP?

So, a global variable can be declared just like other variable but it must be declared outside of function definition. Syntax: $variable_name = data; Below programs illustrate how to declare global variable.

Are there global variables in PHP?

$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.

What is ESC in CodeIgniter?

Escapes data for inclusion in web pages, to help prevent XSS attacks. This uses the Laminas Escaper library to handle the actual filtering of the data. If $data is a string, then it simply escapes and returns it. If $data is an array, then it loops over it, escaping each 'value' of the key/value pairs.

What is constant in CodeIgniter?

CodeIgniter provides a few functions and variables that are globally defined, and are available to you at any point. These do not require loading any additional libraries or helpers. Global Functions.


1 Answers

You should probably put it into a Library, and autoload the library. When you need to use the "logged_in" flag in a view, pass it in from the controller. Example:


application/libraries/Auth.php

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Auth
{

    public function is_logged_in ()
    {
        // Change this to your actual "am I logged in?" logic
        return $_SESSION['logged_in'];
    }

}

application/config/autoload.php

...
$autoload['libraries'] = array(
    ...
    'auth',
    ...
}

`application/controllers/welcome.php

<?php ...

public function index ()
{
    $view_data = array
    (
        'logged_in' => $this->Auth->logged_in()
    );
    $this->load->view('my_view', $view_data);
}

application/views/my_view.php

<? echo $logged_in ? 'Welcome back!' : 'Go login!' ?>
like image 116
Joe Avatar answered Sep 30 '22 08:09

Joe