Download and Install CodeIgniter 4
Download the latest version of CodeIgniter 4 and unzip source code to new folder named LearnCodeIgniter4WithRealApps
Cut index.php and htaccess files in public folder to root folder of project
Open index.php in root folder find to line 16 replace path to Paths.php file as below:
$pathsPath = realpath(FCPATH . '/app/Config/Paths.php');
Open App.php in app/Config folder find to line 39 remove index.php string in $indexPage variable as below:
public $indexPage = '';
Set BASE URL
Open App.php file in app/Config folder. Set value for $baseURL variable as below:
public $baseURL = 'http://localhost:8091/LearnCodeIgniter4WithRealApps/';
Create Controller
Create new PHP file named Demo.php in app/Controllers folder as below:
<?php
namespace App\Controllers;
class Demo extends BaseController
{
public function index()
{
session()->set('id', 123);
session()->set('username', 'acc1');
session()->set('product', array(
'id' => 'p01',
'name' => 'name 1',
'price' => 4.5
));
session()->set('fullName', 'Name 1');
// Remove Session
session()->remove('fullName');
return $this->response->redirect(site_url('demo/index2'));
}
public function index2()
{
if (session()->has('id')) {
$data['id'] = session('id');
}
if (session()->has('username')) {
$data['username'] = session('username');
}
if (session()->has('product')) {
$product = session('product');
$data['product'] = $product;
}
if (session()->has('fullName')) {
$data['fullName'] = session('fullName');
}
return view('demo/index', $data);
}
}
Create View
Create new folder named demo in app/Views folder. In this folder, create new PHP file named index.php as below:
<html>
<head>
<title>Session in Codeigniter 4</title>
</head>
<body>
<h3>Index</h3>
Id: <?= $id ?>
<br>
Username: <?= $username ?>
<br>
Product Id: <?= $product['id'] ?>
<br>
Product Name: <?= $product['name'] ?>
<br>
Price: <?= $product['price'] ?>
<br>
Full Name: <?= isset($fullName) ? $fullName : '' ?>
</body>
</html>
Define Routes
Open Routes.php file in app/Config folder. Set default controller as below:
$routes->get('/', 'Demo::index');
$routes->get('/demo/index2', 'Demo::index2');
Structure of CodeIgniter 4 Project
Run Application
Access index action in Demo controller with following url: http://localhost:8095/LearnCodeIgniter4WithRealApps/demo/index
Output