Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

codeigniter 4 set session variable $session = \Config\Services::session(); globally

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.

like image 827
dharmx Avatar asked Apr 29 '20 10:04

dharmx


People also ask

How do you set a session value in CI?

$_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() .

How do you destroy a session in ci4?

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.

How can get CI session ID?

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.

What are sessions in CodeIgniter?

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.


1 Answers

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");

    }

    //--------------------------------------------------------------------

}
like image 128
dharmx Avatar answered Sep 30 '22 09:09

dharmx