Read local regular files completely, by range, by prefix, by tail, or lazily as chunks and lines. Supports explicit byte limits without runtime package dependencies.
composer require componenta/file-reader:^1.0Requires PHP 8.4 or later (within PHP 8.x). No runtime package dependencies.
use Componenta\Stdlib\FileReader;
$content = FileReader::read($authorizedPath);
$bounded = FileReader::read($authorizedPath, maxBytes: 1024 * 1024);
$prefix = FileReader::readPrefix($authorizedPath, maxBytes: 8192);
$range = FileReader::readRange($authorizedPath, offset: 128, length: 64);
$tail = FileReader::readTail($authorizedPath, length: 4096);The application must authorize the path before reading. Only local regular files are supported; symlinks to regular files are allowed. The reader owns its file handle and never modifies the file. Synchronous methods close it before returning; lazy methods retain it only for the lifetime of their generator.
Stateless utility with six static operations.
read(string $path, ?int $maxBytes = null, FileReadLock $lock = FileReadLock::None): string
Reads the entire file from its beginning. When a limit is supplied, rejects a file that exceeds it, including growth during the read. Does not return a truncated successful result.
| Argument | Description |
|---|---|
$path |
Caller-authorized local regular file path. Absolute or relative. |
$maxBytes |
Maximum permitted size in bytes; nonnegative. null (default) means no explicit byte limit. Zero permits only an empty file. |
$lock |
Shared-lock mode; defaults to FileReadLock::None. |
Returns: Binary-safe file contents, or an empty string for an empty file.
Exceptions: InvalidArgumentException for a negative limit; FileExceptionInterface for acquisition, I/O or size-limit failures (including FileSizeLimitException).
readPrefix(string $path, int $maxBytes, FileReadLock $lock = FileReadLock::None): string
Reads at most the requested number of bytes from the beginning. A longer file is allowed.
| Argument | Description |
|---|---|
$path |
Caller-authorized local regular file path. Absolute or relative. |
$maxBytes |
Maximum bytes returned; nonnegative. Zero still validates and opens the file, but returns no bytes. |
$lock |
Shared-lock mode; defaults to FileReadLock::None. |
Returns: Binary-safe prefix, which may be shorter than the limit at EOF.
Exceptions: InvalidArgumentException for a negative limit; FileExceptionInterface for acquisition or I/O failures. Exceeding the limit is not itself an error for a prefix.
readRange(string $path, int $offset, int $length, FileReadLock $lock = FileReadLock::None): string
Reads a binary range from the given byte offset, without loading the preceding bytes. A positive offset at or beyond the opened file's reported size returns an empty string.
| Argument | Description |
|---|---|
$path |
Authorized local regular file path. |
$offset |
Nonnegative zero-based byte position. |
$length |
Maximum number of returned bytes; nonnegative. |
$lock |
Shared-lock mode; defaults to FileReadLock::None. |
Returns: At most $length bytes, possibly fewer at EOF. Zero length still validates and opens the file.
Exceptions: InvalidArgumentException for a negative offset or length; FileExceptionInterface for acquisition, positioning or I/O failures.
readTail(string $path, int $length, FileReadLock $lock = FileReadLock::None): string
Reads the last requested bytes based on the opened file's reported size. If the file is shorter, reads its available contents. Concurrent changes may affect the result; pseudo-files reporting zero size yield an empty tail.
| Argument | Description |
|---|---|
$path |
Authorized local regular file path. |
$length |
Maximum number of returned bytes; nonnegative. |
$lock |
Shared-lock mode; defaults to FileReadLock::None. |
Returns: Bytes in their original order, at most $length. Zero length still validates and opens the file.
Exceptions: InvalidArgumentException for a negative length; FileExceptionInterface for acquisition, positioning or I/O failures.
readChunks(string $path, int $chunkSize = 65536, ?int $maxBytes = null, FileReadLock $lock = FileReadLock::None): Generator
Reads a file incrementally. Each yielded chunk is nonempty and has exactly $chunkSize bytes, except the final chunk if shorter. Empty files yield nothing.
| Argument | Description |
|---|---|
$path |
Authorized local regular file path. |
$chunkSize |
Positive number of bytes per yielded chunk; defaults to 64 KiB. |
$maxBytes |
Optional nonnegative total file byte limit. null means unlimited. |
$lock |
Shared-lock mode; defaults to FileReadLock::None. |
Returns: A one-shot Generator<int, string, mixed, void> with consecutive zero-based keys.
Exceptions: InvalidArgumentException for invalid numeric arguments at call time; FileExceptionInterface during iteration, including FileSizeLimitException for an oversized file.
readLines(string $path, ?int $maxBytes = null, ?int $maxLineBytes = null, FileReadLock $lock = FileReadLock::None): Generator
Reads LF-delimited lines as binary strings. LF and CRLF terminators are preserved; a lone CR is data. Empty lines are returned, a trailing LF does not create an additional empty line, and a final unterminated line is returned as-is. No character encoding conversion or BOM removal is performed.
| Argument | Description |
|---|---|
$path |
Authorized local regular file path. |
$maxBytes |
Optional nonnegative total file byte limit. null means unlimited. |
$maxLineBytes |
Optional nonnegative limit for one line, including its terminator. null means unlimited. |
$lock |
Shared-lock mode; defaults to FileReadLock::None. |
Returns: A one-shot Generator<int, string, mixed, void> with consecutive zero-based keys. An empty file yields nothing.
Exceptions: InvalidArgumentException for negative limits at call time; FileExceptionInterface during iteration, including FileSizeLimitException and FileLineSizeLimitException.
use Componenta\Stdlib\FileReader;
foreach (FileReader::readChunks($authorizedPath, chunkSize: 65536) as $chunk) {
// Process this chunk without accumulating the whole file.
}
foreach (FileReader::readLines($authorizedPath, maxLineBytes: 65536) as $line) {
// Process this line, including its original terminator.
}Numeric arguments are checked immediately; path validation and opening occur at first iteration. Relative paths are resolved at that time. Exhaustion or failure closes the handle. Breaking a loop while retaining its generator does not close the handle: release all references to that generator if it is no longer needed. A closing failure may be reported when the last reference is released, not only when iterating to exhaustion. Separate calls create independent generators. Small logical chunks may be read ahead into a bounded 64 KiB buffer; delivery never exceeds the configured byte limit. Temporary PHP error handlers are not active while iteration is suspended.
An initial oversized file fails before any item is yielded. A later I/O or size-limit failure may occur after items have been delivered; earlier items are not rolled back. Consumers requiring all-or-nothing side effects must provide their own transaction or use a synchronous read. Memory for chunks depends on the chunk size, and memory for lines depends on the longest line; retaining yielded items defeats incremental processing.
FileReadLock is an optional policy shared by all six methods. Existing calls do not acquire a lock.
| Case | Behavior |
|---|---|
None |
No lock is acquired (default). |
Shared |
Wait for a shared lock (LOCK_SH); there is no reader-imposed timeout. |
SharedNonBlocking |
Try to acquire a shared lock without waiting (LOCK_SH + LOCK_NB). |
use Componenta\Stdlib\Exception\FileLockException;
use Componenta\Stdlib\FileReader;
use Componenta\Stdlib\FileReadLock;
$content = FileReader::read($authorizedPath, maxBytes: 1048576, lock: FileReadLock::Shared);
try {
$prefix = FileReader::readPrefix($authorizedPath, 8192, lock: FileReadLock::SharedNonBlocking);
} catch (FileLockException $error) {
if (!$error->wouldBlock) {
throw $error;
}
// Another incompatible lock prevented acquisition.
}The reader verifies the opened regular file before acquiring its lock and refreshes its metadata afterwards. A cooperating writer may have changed the size while a reader was waiting. The limit and range/tail positioning therefore use the post-lock size. Even a zero-length read acquires the requested lock.
Shared locks allow other shared readers. They coordinate with writers that acquire an exclusive lock on the same file. The reader holds its lock until the owned descriptor is closed, including while a generator is suspended. For lazy methods, acquisition occurs on first iteration, not when creating the generator. A retained generator after break still holds its lock; release it promptly to avoid delaying writers.
If acquisition fails or PHP's native flock() function is disabled, FileLockException is thrown. Unlocked reads do not require flock(). Its wouldBlock property is true only when PHP reports lock contention for nonblocking acquisition; other failures have false. An underlying native exception is retained in getPrevious() when available.
Locks may be advisory, depending on platform and filesystem. Writers must cooperate; locking an opened file does not protect the path against replacement or provide an atomic snapshot against uncooperative writes. Blocking mode can wait indefinitely and blocks the PHP execution context. Nonblocking mode avoids waiting for lock acquisition, but is not asynchronous file I/O.
All expected file failures implement FileExceptionInterface, in Componenta\Stdlib\Exception.
| Exception | Meaning |
|---|---|
InvalidFileException |
Invalid path, unsupported wrapper or nonregular file. |
FileUnavailableException |
Path cannot be resolved or accessed. |
FileReadException |
Opening, inspecting, positioning, reading or closing the handle failed. |
FileCloseException |
Closing the owned handle failed; extends FileReadException. |
FileLockException |
A requested shared lock could not be acquired. |
FileSizeLimitException |
A complete read would exceed the requested byte limit. |
FileLineSizeLimitException |
A line exceeds the configured byte limit. |
FileSizeLimitException::$maxBytes and FileLineSizeLimitException::$maxLineBytes are the rejected limits in bytes. FileReadException::$readFailure is the earlier failure if closing also failed; getPrevious() retains the closing cause or underlying native error when available. Unexpected programming errors are not converted into ordinary file failures when cleanup succeeds.
use Componenta\Stdlib\Exception\FileExceptionInterface;
use Componenta\Stdlib\Exception\FileSizeLimitException;
use Componenta\Stdlib\FileReader;
try {
$content = FileReader::read($authorizedPath, maxBytes: 1024 * 1024);
} catch (FileSizeLimitException $error) {
// Reject oversized content.
} catch (FileExceptionInterface $error) {
// Handle file acquisition or I/O failure.
}URLs, stream wrappers, paths containing NUL, directories and special files are rejected. The reader verifies file type and checks identity where supported; stale path resolution can trigger invalidation of PHP's realpath cache. These checks are not an authorization boundary and cannot eliminate filesystem races. Without a requested shared lock, the file may change in place during reading. Even with a lock, the reader cannot promise an atomic filesystem snapshot against uncooperative writers. A byte limit is not an absolute memory or execution-time limit. Native platform behavior and available filesystem identity information affect these guarantees.
readAdaptivePrefix(string $path, int $probeBytes, int $maxBytes, callable $requiresMore, FileReadLock $lock = FileReadLock::None): string reads a positive initial prefix within the total budget. After each complete prefix and while more bytes are allowed, the callback is called. true extends to the budget, false stops, and an integer requests a strictly greater total prefix length within the budget. Short probes at EOF and exhausted budgets do not call the callback. All stages use one opened descriptor and the same lock, if requested. No path is reopened. The callback runs synchronously outside the native error handler and must not acquire a conflicting lock on the file. Callback failures propagate unchanged unless close also fails; both failures are then retained. This does not make concurrent file writes an atomic snapshot. Existing readPrefix behavior is unchanged.