Use Images, CSS and JavaScript in 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 36 remove index.php string in $indexPage variable as below:

public $indexPage = '';




Open App.php file in app/Config folder. Set value for $baseURL variable as below:

public $baseURL = 'http://localhost:8095/LearnCodeIgniter4WithRealApps/';

Create new folder named assets in public folder. In this folder, create new folders as below:

Create new folder named images in assets folder. Copy images need to use in project to images folder.

Create new folder named css in assets folder. In this folder, create new css file named style.css as below:

.format-text {
	color: red;
	font-size: 20px;
}

img {
	width: 120px;
	height: 100px;
}

Create new folder named js in assets folder. In this folder, create new javascript file named mylib.js as below:

function clickMe() {
	alert('Hello World');
}




Create new PHP file named Demo.php in app/Controllers folder as below:

<?php

namespace App\Controllers;

class Demo extends BaseController
{
	public function index()
	{
		return view('demo/index');
	}
}

Create new folder named demo in app/Views folder. In this folder, create new PHP file named index.php as below:

<html>
	<head>
		<title>Demo Page</title>
		<link href="<?= base_url(); ?>/public/assets/css/style.css" rel="stylesheet" type="text/css">
		<script src="<?= base_url(); ?>/public/assets/js/mylib.js" type="text/javascript"></script>
	</head>
	<body>

		<h3 class="format-text">Demo Page</h3>
        <img src="<?= base_url(); ?>/public/assets/images/thumb1.gif" onclick="clickMe()">

	</body>
</html>




Open Routes.php file in app/Config folder. Set default controller as below:

$routes->get('/', 'Demo::index');




Access index action in Demo controller with following url: http://localhost:8095/LearnCodeIgniter4WithRealApps/demo/index

Output