read()
public function read(string $file_path): string
Description
Reads and returns the contents of a file. Access is restricted for critical application directories.
Parameters
| Parameter | Type | Description |
| $file_path |
string |
The path to the file to be read. |
Return Value
| Type | Description |
| string |
The contents of the file. |
Example #1
The code sample below demonstrates the most basic file reading operation.
$file_path = 'modules/documents/readme.txt';
// Check if file exists before reading
if ($this->file->exists($file_path)) {
$content = $this->file->read($file_path);
echo $content;
} else {
echo 'File not found';
}
Check Before You Act: The read() method throws an exception if the file doesn't exist or cannot be read. Always verify the file exists using $this->file->exists($file_path) before attempting to read it. This allows you to handle missing files gracefully rather than relying on exception handling.
Example #2
The example above shows how to read and process a CSV file.
public function import_contacts(): void {
$import_id = segment(3, 'int');
// Get import record
$import = $this->db->get_where($import_id, 'imports');
if ($import === false) {
redirect('imports/not_found');
}
$file_path = 'modules/imports/uploads/' . $import->filename;
if (!$this->file->exists($file_path)) {
redirect('imports/file_not_found');
}
// Read the CSV file
$csv_content = $this->file->read($file_path);
$rows = array_map('str_getcsv', explode("\n", $csv_content));
// Skip header row and process data
$imported = 0;
for ($i = 1; $i < count($rows); $i++) {
if (count($rows[$i]) >= 3) {
$data = [
'name' => $rows[$i][0],
'email' => $rows[$i][1],
'phone' => $rows[$i][2]
];
$this->model->insert($data, 'contacts');
$imported++;
}
}
set_flashdata("Imported {$imported} contacts");
redirect('contacts/manage');
}
Example #3
The example above demonstrates how to read a configuration file and parse its contents.
public function load_settings(): array {
$settings_file = 'modules/settings/config/app_settings.json';
if (!$this->file->exists($settings_file)) {
// Return default settings if file doesn't exist
return [
'site_name' => 'My Application',
'maintenance_mode' => false,
'max_upload_size' => 5242880
];
}
// Read and parse JSON configuration
$json_content = $this->file->read($settings_file);
$settings = json_decode($json_content, true);
if (json_last_error() !== JSON_ERROR_NONE) {
// Handle invalid JSON
throw new Exception('Invalid settings file format');
}
return $settings;
}
Example #4
The example above shows how to read a log file and display its most recent entries.
public function view_recent_logs(): void {
$log_file = 'modules/admin/logs/application.log';
if (!$this->file->exists($log_file)) {
$data['log_entries'] = [];
$this->view('logs', $data);
return;
}
// Read the entire log file
$log_content = $this->file->read($log_file);
// Split into individual lines
$all_lines = explode("\n", trim($log_content));
// Get the last 50 entries
$recent_entries = array_slice($all_lines, -50);
// Reverse so newest appears first
$recent_entries = array_reverse($recent_entries);
$data['log_entries'] = $recent_entries;
$data['total_entries'] = count($all_lines);
$this->view('logs', $data);
}
Memory Considerations: The read() method loads the entire file contents into memory. For very large files (several megabytes or more), consider using PHP's native streaming functions like fopen() and fgets() to process the file line-by-line instead of loading it all at once.
Security Note: The method automatically validates paths to prevent access to restricted system directories (like config and engine). Attempting to read files from protected directories will throw an exception with the message "Access to this path is restricted".