write()

public function write(string $file_path, mixed $data, bool $append = false): bool

Description

Writes or appends data to a file. This method includes path validation to prevent writing to restricted application areas.

Parameters

ParameterTypeDescription
$file_path string The path to the destination file.
$data mixed The data to write to the file.
$append bool (optional) Whether to append data instead of overwriting. Default is false.

Return Value

TypeDescription
bool Returns true on successful write.

Example #1

The code sample below demonstrates the most basic file writing operation.

Overwrite vs Append: By default, write() overwrites any existing file content. To add content to the end of an existing file without removing what's already there, set the third parameter to true: $this->file->write($file_path, $data, true).

Example #2

The example above shows how to append log entries to an existing log file.

Example #3

The example above demonstrates how to export database records to a CSV file.

Example #4

The example above shows how to save user preferences to a JSON configuration file.

Example #5

The example above demonstrates how to create a daily report file that gets overwritten each day.

Batch Processing Tip: To convert multiple files at once, you could extend this example to use $this->file->list_directory() to get all files in a directory, then loop through them applying the same conversion process to each file.

Example #6

The example below demonstrates how to convert British English documentation to American English by reading a translation mapping from a JSON file and applying it to a target documentation file.

The View File

Create a view file at modules/documentation/views/british_to_american_mappings.php containing only the JSON array. The view() method with the third parameter set to true returns the raw content as a string instead of rendering it to the browser.

Directory Must Exist: The write() method will create the file if it doesn't exist, but it will not create the parent directory. Always ensure the destination directory exists before writing files, either by checking with $this->file->exists($directory) or by creating it with $this->file->create_directory($directory).

Security Note: The method automatically validates paths to prevent writing to restricted system directories (like config and engine). Attempting to write to protected directories will throw an exception with the message "Access to this path is restricted".