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?
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.
$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.
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.
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.
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!' ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With