Close

🔰 PHP Programming Tutorial 10 - Session in CodeIgniter 4 🔰


Overview

The Session class allows you to maintain a user’s "state" and track their activity while they browse your site.

Session Initialization

To access and initialize the session:

$session = \Config\Services::session($config);

Example:

$this->session 	= \Config\Services::session();

Add data to the session

set() method is used to add value to the session. It takes two arguments as a parameter first is session name and the second is session value.

$this->session->set('session_name', 'any_value');

We can also use the set() function to pass an array to store values as shown below.

$data = array( 	'username' 	=> 'chirags', 	'email' 	=> 'support@chirags.in', 	'logged_in'	=> TRUE ); $this->session->set($data);

Fetch data from Session

A get() function is used to get data from the session. It takes the session key name as an argument. For example:

$name = $this->session->get('username');

Remove data from Session

We can use remove() function that will remove data from the session.

$this->session->remove('session_name');

If you want to remove more that one value and an array data then you can use the same function remove().

$data = array('username', 'email'); $this->session->remove($data);

Destroying a Session

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. Both will work in exactly the same way:

session_destroy();  // or  $this->session->destroy();

Flashdata

While building a web application, we need to store some data for only one time, and later, we want to remove that data. For example, to display some error message or information message. In CodeIgniter, flashdata will only be available until the next request, and it will get deleted automatically.

Add Flashdata:

$this->session->setFlashdata('item','value');

You can also pass an array to setFlashdata(), in the same manner as set().

$data = array( 	'username' 	=> 'chirags', 	'email' 	=> 'support@chirags.in' ); $this->session->getFlashdata($data);

Retrieve Flashdata:

$this->session->getFlashdata('item');

Or to get an array with all flashdata, simply omit the key parameter:

$this->session->getFlashdata();


😉Subscribe and like for more videos:
https://www.youtube.com/@chiragstutorial
💛Don't forget to, 💘Follow, 💝Like, 💖Share 💙&, Comment

0 Comments
Leave a message

 

Search Current Affairs by date
Other Category List

Cookies Consent

We use cookies to enhance your browsing experience and analyze our traffic. By clicking "Accept All", you consent to our use of cookies. Cookies Policy