Read and Write Files in CodeIgniter 4 Tutorial

Reading Time: 5 minutes
18,303 Views

In web applications generating files, writing dynamic content over files, creating and reading files are mostly common. So here inside this article we will see such type of interesting concept in CodeIgniter 4.

Read and Write Files in CodeIgniter 4, we will do using a helper in codeigniter i.e filesystem. We will do write and read operations over a sample text file.

If you are wondering that where we should use this concept File System, So for an example if you want to make a log of your application of some kind of running processed then by using this concept you can write the log into files and then if need you can read that.

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.


Load filesystem Helper

To access the write function in CodeIgniter 4, we need to load filesystem helper in application. For read operation, readfile is a php function so we don’t want helper but to write files write_file we need to load that.

We have two options to load helper in application

  • By using Parent Controller i.e BaseController.php
  • Loading inside specific controller file

Loading inside BaseController.php

Search for protected $helpers = [];

Write this code inside BaseController.

protected $helpers = ['filesystem'];

Loading Inside Specific Controller

helper("filesystem");

So, here we will use by loading into BaseController.php file.


Create Routes

Open Routes.php file from /app/Config folder. Add these routes into it.

//...

$routes->get("write-file", "Home::writeDataFile");
$routes->get("read-file", "Home::readDataFile");

//...

Next, we need to create a controller file with name Home and two method. One is for write file and other is for read file.


Create Controller

By default Home.php controller file will be available inside /app/Controllers folder when we install CodeIgniter 4.

But if you want to create new file then you can use the same code of Home.php, only you need to modify the name of the controller class.

$ php spark make:controller Home

It will create a file called Home.php inside /app/Controllers.

Open Home.php and write this piece of code.

<?php 

namespace App\Controllers;

class Home extends BaseController
{
	public function writeDataFile(){

		$file_content = "Welcome to Online Web Tutor Blog";

		// Type#1 - This file will be created inside /public folder
		write_file("data.txt", $file_content);

		// Type#2 - This file will be created inside /writable folder
		write_file(WRITEPATH. "data-2.txt", $file_content);

		// Type#3 - Write file inside /public folder and return value
		if (!write_file('data-3.txt', $file_content)){
		   
			echo 'Unable to write the file';
        }else{
		   
			echo 'Successfully file written';
        }
	}

	public function readDataFile(){

		// Type#1 - Read file from /public folder
		$data1 = readfile("./data.txt");

		print_r($data1);

		// Type#2 - Read file from /writable folder
		$data2 = readfile(WRITEPATH. "data-2.txt");

		print_r($data2);
	}
}
  • writeDataFile() method is for writing files. write_file is a function which we have accessed after loading filesystem helper.
  • By default file will be create and write inside /public folder of application which is at root
  • WRITEPATH returns the path of /writable folder. It is a pre defined CodeIgniter 4 constant variable.
  • readfile() is a php function. To use this, we actually don’t need to load any helper. Directly we can use it.

Application Testing

Open project terminal and start development server via command:

php spark serve

Open these URLs to test

Write File – http://localhost:8080/write-file

Read File – http://localhost:8080/read-file

We hope this article helped you to learn about Working with File System in CodeIgniter 4 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.