Single File Upload 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 39 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:8091/LearnCodeIgniter4WithRealApps/';

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

<?php

namespace App\Controllers;

class Demo extends BaseController
{
	public function __construct()
	{
		helper(['url', 'form']);
	}

	public function index()
	{
		return view('demo/index');
	}

	public function doUpload()
	{
		$file = $this->request->getFile('photo');
		$randomName = $file->getRandomName();
		$data['fileName'] = $file->getName();
		$data['randomName'] = $randomName;
		$data['fileType'] = $file->getClientMimeType();
		$data['fileSize'] = $file->getSize();
		$file->move('public/uploads', $randomName);
		return view('demo/success', $data);
	}
}						

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

Index View

In demo folder, create new PHP file named index.php as below:

<html>

<head>
	<title>Single File Upload in CodeIgniter 4</title>
</head>

<body>

	<h3>Upload File</h3>

	<?= form_open_multipart('demo/do_upload'); ?>
		<input type="file" name="photo" />
		<br /><br />
		<input type="submit" value="Upload" />
	<?= form_close(); ?>

</body>

</html>

Success View

In demo folder, create new PHP file named success.php as below:

<html>

<head>
	<title>Single File Upload in CodeIgniter 4</title>
</head>

<body>

	<h3>File Info</h3>
	File Name: <?= $fileName ?>
	<br>
	Random Name: <?= $randomName ?>
	<br>
	File Type: <?= $fileType ?>
	<br>
	File Size(byte): <?= $fileSize ?>
	<br>
	<img src="<?= base_url() ?>/public/uploads/<?= $randomName ?>" width="120">

</body>

</html>
			

Open Routes.php file in app/Config folder and define routes as below:

$routes->get('/', 'Demo::index');
$routes->post('/demo/do_upload', 'Demo::doUpload');

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

Output