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

ParameterTypeDescription
$file_path string The path to the file to be read.

Return Value

TypeDescription
string The contents of the file.

Example #1

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

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.

Example #3

The example above demonstrates how to read a configuration file and parse its contents.

Example #4

The example above shows how to read a log file and display its most recent entries.

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".