in codeigniter 4 as per the documentation we have to load library as
$session = \Config\Services::session();
if i write it on above of controller name
<?php
namespace App\Controllers;
$session = \Config\Services::session();
class Home extends BaseController
{
}
i cant access $session variable in any function, even if i wrote it in __construct it is not accessible in any function if i write it any function then only it is working, but i wants to set it globally.
$_SESSION['item'] = 'value'; $this->session->mark_as_flash('item'); Or alternatively, using the set_flashdata() method: $this->session->set_flashdata('item', 'value'); You can also pass an array to set_flashdata() , in the same manner as set_userdata() .
To clear the current session (for example, during a logout), you may simply use either PHP's session_destroy() function, or the library's destroy() method.
You have to load session library. Add a __construct method to the Login controller and load the library. This will let you access to the library's functions in any method inside the controller.
The Session class permits you to maintain a user's “state” and track their activity while they browse your site. CodeIgniter comes with a few session storage drivers, that you can see in the last section of the table of contents: Using the Session Class.
i solved it, as below
<?php
namespace App\Controllers;
class Home extends BaseController
{
protected $session;
function __construct()
{
$this->session = \Config\Services::session();
$this->session->start();
}
public function code4()
{
$newdata = [
'username' => 'johndoe',
'email' => '[email protected]',
'logged_in' => TRUE
];
$this->session->set($newdata); // setting session data
echo $this->session->get("username");
}
//--------------------------------------------------------------------
}
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