Unable to set session in codeigniter

If you are unable to set session data in Codeigniter you can follow this code snippet to set the session data and after that, you can display it anywhere in your project’s view and controller’s method using this particular session name.

Answers 1
  • Set session data and display in codeigniter 4

    <?php
    //Set session data to controller's method.
    //app\Controllers\<Home>.php
     
    public function setSessionData(){
        // Initializing session
        $session = session();
        // Adding session data
        $session->set('name', 'Samar');
        // You can also get session data in controller method 
        //echo $session->get('name');
        return view('home');
    }
    
    
    //Display session data in view file
    //app\Views\<home>.php
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <p> You can get session data using session name in any view file </p>
        <?php 
            $session = session();
            echo $session->get('name');
        ?>
    </body>
    </html>
    
    0

    In Codeigniter 4 you can set session data in the controller's method by initializing the session variable and after that add session data to this session variable by passing the value using the set method. You can access this session data anywhere in your project like the controller's method and in any view file.

  • Back to code snippet queries related codeIgniter