CodeIgniter 4 How To Work with Session Library Tutorial

Reading Time: 6 minutes
17,686 Views

Inside this article we will see the concept i.e CodeIgniter 4 How To Work with Session Library Tutorial. Article contains the classified information about Session service and it’s methods to manage user data.

In any application, maintaining user session data and it’s activity is very important. It keeps track of every operation performed by user. By the help of session library or driver we can actually manage user session.

To use CodeIgniter 4 session library, we have some different approach from older versions, the Session library which is a class that permits us to maintain a user’s state and it’s data and track their activity while they browse any site.

Learn More –

Let’s get started.

CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Environment (.env) Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

Open project in terminal

cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.

How to use a Session Class?

When we define a session variable or it’s value, it will be typically run globally with each page load. So the Session class should be magically initialized so that we can access that variable and it’s value we can access anywhere.

To initialize the session:

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

$config is an optional parameter. We can pass some configuration while initialization. Once we done the load, we can access $session anywhere in the application.

Alternatively, we can load session like this $session = session(); We can say it’s a shorthand way to load.

Session class we can find at this path – /vendor/codeigniter4/framework/system/Session/Session.php

What is Session data?

Session data means the key value pairs which we store into session to maintain user state across application. In Core PHP we usually use $_SESSION[‘key’] = ‘value’;

Here, inside this CodeIgniter 4, we will use few methods available which helps to store data, retrieve data, remove data etc.

Session Methods of CodeIgniter 4

As we already discussed that by the help of session class library, we do all operations like store, get, remove, destroy etc.

To accomplish the following tasks, we have several methods available in Session class library which reduces effort and do easily. Here are the following methods –

  • $session->set(“key”, “value”); To store value in session. Value will be either a single value or it can be an array.
  • $session->push(“key”, “newvalue”); To add new value to specified key. It key will be an array variable then it adds the new value to array.
  • $session->get(“key”); OR session(“key”); [ This is by using session helper function ] OR $session->key to get session value on the basis of specified key.
  • $session->remove(“key”); It removes the key what we have put here from session data.
  • $session->destroy(); This method destroy the complete session data from session what we have stored.
  • $session->has(“key”); To check session key exists or not.
  • $session->setFlashdata(“key”, “value”); To store flashdata means temporary data into session. It’s a one time use data only.
  • $session->getFlashdata(“key”); To get a stored flash data from session. Instead of using this way also we have an alternative option by using helper function of session session()->get(“key”);

Let’s use the session methods.

Usage of CodeIgniter 4 Session Library

We can use session methods in controller.

Learn More –

Session Initialization

We can load or create a session instance directly into any methods or best way to do in constructor of class.

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

OR

$session = session();

Store Value in Session

# Single value
$session->set("username", "onlinewebtutorblog");

# Multiple values
$session->set("userdata", array(
   "name" => "Sanjay",
   "emp_id" => 1001,
   "email" => "sanjay_test@sample.com"
 ));

Read Session Value

$session->get("username");

OR

$session->username;

OR

session("username");

Remove Session Value

# Single value
$session->remove("username");

OR

# Complete session value
$session->destroy();

Store a Flash message

$session->setFlashdata("success", "Post has been added successfully");

Display a Flash message

session()->get("success");

Additionally, we can change session preferences or session settings at /app/Config/App.php. Configuration includes sessionDriver, sessionCookieName, sessionExpiration, sessionMatchIP etc.

To learn more about CodeIgniter 4 Session library also you can go through this official document Click here. We have an article which helps to prevent from Session hijack attacks Click here to go.

We hope this article helped you to learn about CodeIgniter 4 How To Work with Session Library Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.