Session variable not printing in view in Codeigniter 4

Viewed 6180

in codeigniter 4 I have tried to print the session variable in view using $session->get('item'); and $session->item as well but unfortunately it does not print. But same variables are printed using $_SESSION global variable. can any one guide how to print in view using $session->get('item'); or $session->item.

The session variables are printing in controller by both methods $session->get('item'); and $session->item.

1 Answers

It's an interesting topic.

Here is some code I used to test this out...

I hijacked the default Home Controller app/Controllers/Home.php

protected $session;
public function index()
{
    $this->session = \Config\Services::session();
    $this->session->set('view_data','Hi there I am from the session');

    $page['view_data'] =$this->session->get('view_data'); // Normal way
    $page['session'] =$this->session;                     // Pass in the object

    echo view('test_session_view',$page);

}

Then I created a little test file to see what would work...

app/views/test_session_view.php

<?php
    $local_session = \Config\Services::session(); // Needed for Point 5
?>
<h1>Test_Session_View.php</h1>
<h2>1. Passed in as normal view variable : <?= $view_data; ?></h2>
<h2>2. Passed in as the Session Object : <?= $session->get('view_data'); ?></h2>
<h2>3. The Ole Fashioned SESSION Global way: <?= $_SESSION['view_data']; ?></h2>
<h2>4. The Helper Way: <?= session('view_data'); ?></h2>
<h2>5. The local instance: <?= $local_session->get('view_data'); ?></h2>

By default $session (in my case $this->session) is not "global" and so it has to obey the same rules as any other variable passed into a View.

Of course, as you noted, $_SESSION, is directly accessible as it is GLOBAL.

And the session helper (Point 4) gives us even simpler access, as you found.

This led to Point 5 which is what the session helper does. It creates an instance of the session and performs a "get". That is in System\Common.php Line 877ish function session(string $val = null)

So there are a few ways you can access session data in a view.

Related