PHP Luminova: Filesystem Operations
File Manager is a helper class shipped with Luminova Framework to handle file-related operations like downloading, reading or writing files, all methods are defined as static making it easier to call.
The Filesystem class provides a set of helper methods for managing files and directories. It simplifies common file operations, including checking existence, reading and writing content, streaming large files, copying, moving, deleting, creating directories, and managing permissions.
Features:
- Easy initialization with file paths using constructor or
info()method. - Access file properties dynamically through SplFileInfo.
- Read and write files safely with support for streams, locks, and chunked operations.
- Recursive directory operations like copy, move, and delete.
- Permission management and Unix permission conversions.
- Symlink creation compatible with Unix and Windows.
This class is ideal for working with the filesystem both in Luminova applications, providing safe and efficient file handling.
Examples
Creating a Filesystem Instance
use Luminova\Storage\Filesystem;
// Using constructor
$fs = new Filesystem('/path/to/file.txt');
// Using static info method
$fs = Filesystem::info('/path/to/file.txt');
// Using Factory Helper
$fs = Luminova\Foundation\Module\Factory::filesystem('/path/to/file.txt');
// Using Helper Function
$fs = Luminova\Funcs\factory(
context: 'filesystem',
shared: true,
arguments: '/path/to/file.txt'
);Access Application Paths.
Using helper functions to access application paths.
System Paths:
echo $fs->views;
// Windows: /resources/Views/
// Unix: \\resources\\Views\\Setting or Updating the File
$fs->setFilename('/new/path/to/file.txt');Now $fs has file info loaded and you can access properties.
Checking if a File or Directory Exists
if ($fs->exists()) {
echo "File exists!";
} else {
echo "File does not exist!";
}Accessing File Properties Dynamically
echo $fs->size; // File size in bytes
echo $fs->extension; // File extension
echo $fs->pathname; // Full path
echo $fs->filename; // file.txt
echo $fs->realPath; // /full/path/to/file.txt
echo $fs->owner; // UID of ownerYou can also call any SplFileInfo method:
echo $fs->getFilename(); // Same as $fs->filenameReading File Contents
$content = Filesystem::contents('/path/to/file.txt');
if ($content !== false) {
echo $content;
}Read only a portion of the file:
$content = Filesystem::contents('/path/to/file.txt', 100, 50);
// Reads 100 bytes starting at offset 50Writing a string
Filesystem::write('/path/to/file.txt', 'Hello World!');Appending to a file
Filesystem::write('/path/to/file.txt', "\nNew line", FILE_APPEND | LOCK_EX);Writing from a stream
$stream = fopen('php://memory', 'rb+');
fwrite($stream, 'Stream content');
rewind($stream);
Filesystem::write('/path/to/file.txt', $stream, FILE_APPEND | LOCK_EX);Streaming Large Files
$position = 0;
Filesystem::read('/path/to/largefile.zip', length: 1024*1024, position: $position);- Reads in chunks (2MB default)
- Updates
$positionafter each read
Creating Directories
Filesystem::mkdir('writeable/storages/images', 0755);- Automatically creates parent directories if they don’t exist.
Copying Files or Directories
$copied = 0;
Filesystem::copy('source/folder', 'dest/folder', skipIfExists: true, copied: $copied);
echo "Copied $copied files.";Moving Files or Directories
$moved = 0;
Filesystem::move('source/folder', 'dest/folder', skipIfExists: true, moved: $moved);
echo "Moved $moved files.";Deleting Files or Directories
$deleted = 0;
Filesystem::delete('writeable/storages/temp', deleteBase: true, deleted: $deleted);
echo "Deleted $deleted items.";Creating a Symbolic Link
Filesystem::symbolic('/path/to/target', '/path/to/symlink');- Automatically creates the destination folder if needed
- Replaces existing links
File Size Utility
echo Filesystem::size('/path/to/file.txt'); // Returns bytes
echo Filesystem::size('folder'); // Returns total folder sizeWorking with Permissions
Convert numeric permission to string
echo Filesystem::permissions(0755); // Output: rwxr-xr-xConvert string permission to Unix number
echo Filesystem::toUnixPermission('rw-r--r--'); // Output: 0644Set file or folder permission
Filesystem::setPermission('/path/to/file.txt', 0644);Class Definition
- Class namespace:
Luminova\Storage\Filesystem
Properties
system
Path to the system framework codes.
protected string $systemplugins
Path to the system third-party plugins.
protected string $pluginslibrary
Path to the libraries and third-party modules.
protected string $libraryservices
Path to the serialized shared services.
protected string $servicescontrollers
Path to the application controllers.
protected string $controllerswriteable
Path to the writeable files.
protected string $writeablelogs
Path to the error logs.
protected string $logscaches
Path to the application caches.
protected string $cachespublic
Path to the public controller document root.
protected string $publicassets
Path to the public assets directory.
protected string $assetsviews
Path to the template views files.
protected string $viewsroutes
Path to the application routes.
protected string $routeslanguages
Path to the languages modules.
protected string $languagesMethods
setPermission
Set permissions for a file or directory.
public static setPermission(string $location, int $permission): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$location | string | The path to the file or directory. |
$permission | int | The permission to set (Unix file permissions e.g, 0777). |
Return Value:
bool - Returns true on success, false on failure.
permissions
Converts Unix file permission code to its string representation.
public static permissions(int $permission): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$permission | int | The unix file permission (e.g, 0777). |
Return Value:
string - Return permission string representation.
write
Write or append data to a file.
This method supports writing both string content and stream resources. It handles optional append mode, file locks, include path, and binary content detection.
public static write(
string $filename,
mixed $content,
int $flags = 0,
int $retries = 5,
int $delay = 50_000,
?resource $context = null,
int &$bytes = 0
): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$filename | string | Path to the file to write. |
$content | string|resource | The data to write, either as a string or a stream resource. |
$flags | int | Optional file flags (e.g., FILE_APPEND, FILE_USE_INCLUDE_PATH, LOCK_EX). |
$retries | int | Number of times to retry acquiring the lock in non-blocking mode. |
$delay | int | Delay in microseconds between retries (default 50_000 = 50ms).. |
$context | resource|null | Optional stream context created via stream_context_create(). |
&$bytes | int | The number of bytes written, or 0 on error. |
Return Value:
bool - Returns true if writing succeeds, false otherwise.
Throws:
- \Luminova\Exceptions\FileException - If the provided stream is invalid or writing fails.
Examples:
Write string:
Filesystem::write('/path/to/file.txt', 'Hello World', FILE_APPEND | LOCK_EX);Write from stream:
$stream = fopen('php://memory', 'rb+');
fwrite($stream, 'Hello Stream');
rewind($stream);
Filesystem::write('/path/to/file.txt', $stream, FILE_APPEND | LOCK_EX);mkdir
Create a directory if it does not exist.
This method attempts to create the directory with the specified permissions.Supports recursive creation of nested directories.
public static mkdir(string $path, int $permissions = 0777, bool $recursive = true): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$path | string | The directory path to create. |
$permissions | int | Unix file permissions (default: 0777, fully accessible to all users). |
$recursive | bool | Whether to create nested directories recursively (default: true). |
Return Value:
bool - Returns true if the directory already exists or was successfully created, false otherwise.
Throws:
\Luminova\Exceptions\FileException - If unable to create the directory due to filesystem errors.
Example:
Filesystem::mkdir('writeable/storages/images', 0755);copy
Recursively copy files and directories from a source to a destination.
Optionally skip files or directories that already exist in the destination.
public static copy(string $origin, string $dest, bool $skipIfExists = false, int &$copied = 0): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$origin | string | The source directory or file path to copy. |
$dest | string | The destination directory path. |
$skipIfExists | bool | Wether to skip already existing files or directories (default: false). |
$copied | int | Reference to store the number of successfully copied items. |
Return Value:
bool - Returns true if at least one file or directory was copied, false otherwise.
Throws:
- \Luminova\Exceptions\RuntimeException - IIf source directory does not exist or is not readable.
- \Luminova\Exceptions\FileException - If unable to create destination directory due to filesystem errors.
move
Recursively move files and directories from a source to a destination.
Optionally skip files or directories that already exist in the destination.
public static move(string $origin, string $dest, bool $skipIfExists = false, int &$moved = 0): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$origin | string | The source directory or file path to move. |
$dest | string | The destination directory path. |
$skipIfExists | bool | Wether to skip already existing files or directories (default: false). |
$moved | int | Reference to store the number of successfully moved items. |
Return Value:
bool - Returns true if at least one file or directory was moved, false otherwise.
Throws:
- \Luminova\Exceptions\RuntimeException - If the source does not exist or is not readable.
- \Luminova\Exceptions\FileException - If unable to create destination directory due to filesystem errors.
size
Determine the size in bytes of a file, directory, stream, or string.
Supported sources:
- File path: returns file size.
- Directory path: returns cumulative size of all files recursively.
- Stream resource: returns size using fstat (if available).
- String: returns byte length of the string.
public static size(mixed $source): intParameters:
| Parameter | Type | Description |
|---|---|---|
$source | mixed | File path, directory path, stream resource, or string. |
Return Value:
int - Return the calculated size in bytes.
Throws:
\Luminova\Exceptions\FileException - If the source is invalid or does not exist.
read
Streams a file resource to output in chunks.
Automatically handles text or binary files, with optional non-blocking reads and resumable positions. Large files are streamed in chunks to reduce memory usage. The file stream is always closed after reading.
public static read(
resource|string $source,
?int $filesize = null,
MIME|string|null $mime = null,
int $length = (1 << 21),
int $delay = 0,
int &$position = 0,
bool $nonBlocking = false
): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$source | resource|string | File stream or file path. |
$filesize | int|null | Optional known file size in bytes, auto-detected if null (default: null). |
$mime | Luminova\Utility\MIME|string|null | Optional MIME type for content detection. Used to determine read method. |
$length | int | Maximum read chunk size in bytes (default: 2MB). |
$delay | int | Delay in microseconds between chunk reads. |
&$position | int | Starting position in the file; updated to final read position (default: 0). |
$nonBlocking | bool | If true, read in non-blocking mode. |
Return Value:
bool - Returns true if the file was successfully streamed; false on error.
Example
Read from resource.
$filename = 'large-file.pdf';
$handler = fopen($filename, 'rb')
FileManager::read($handler, nonBlocking: true);Read directory from file path.
FileManager::read('/path/to/file.pdf', nonBlocking: true);download
Download a file to the user's browser with optional delay between chunks.
public static download(
string|resource $content,
?string $filename = null,
array $headers = [],
bool $delete = false,
int $chunk_size = 8192,
int $delay = 100000
): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$content | string|resource | The full file path, resource, or string to download. |
$filename | string|null | The filename as it will be shown in the download (e.g, image.png). |
$headers | array<string,mixed> | Optional array headers for download.. |
$delete | bool | Whether to delete the file after download (default: false). |
$chunk_size | int | The size of each chunk in bytes for large content (default: 8192, 8KB). |
$delay | int | The delay between each chunk in microseconds (default: 100000, 0.1 second). |
Return Value:
bool - Return true on success, false on failure.
Supported Download Content $content
- File path - Download content from path specified.
- Resource - Download content from resource specified.
- String - Download content from string specified.
remove
Deletes files and folders recursively.
public static remove(string $location, bool $delete_base = false, int& $deleted = 0): intParameters:
| Parameter | Type | Description |
|---|---|---|
$location | string | Directory or file to delete. |
$delete_base | bool | Remove the base directory once done (default is false). |
$deleted | int | Reference to a variable to store the number of deleted items. |
Return Value:
int - Returns count of deleted files.
symbolic
Create a symlink to a target file or directory.
public static symbolic(string $target, string $link): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$target | string | The targe file or directory to link from. |
$link | string | The location of the link. |
Return Value:
bool - Return true if the link was successfully created false otherwise.
isResource
Checks if a variable is a valid resource of the specified type.
public static isResource(mixed $resource, ?string $type = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$resource | mixed | The resource to check. |
$type | string | The expected resource type. Possible values are: 'stream-context', 'stream', etc. |
Return Value:
bool - Returns true if the variable is a resource and matches the expected resource type, otherwise returns false.
isAccessible
Validate if the provided file path is safe, exists, and is readable.This method checks if the file path is valid, whether it is accessible, and ensures it's readable unless it's a UNC path.
public static isAccessible(string $path): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$path | string | The file path to validate (relative or absolute). |
Return Value:
bool - Returns true if the file is accessible and readable.
isPathPermitted
Verify if the file path follows the allowed format and is not a URL or PHP Archive (Phar).This method ensures that the file path does not use a URL scheme or a phar path, restricting access to local files only.
public static isPathPermitted(string $path): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$path | string | The file path to check (relative or absolute). |
Return Value:
bool - Returns true if the path is a valid local file path.
toUnixPermission
Convert permission string to Unix integer permission.
public static toUnixPermission(string $permission, bool $decimal = false): string|int|nullParameters:
| Parameter | Type | Description |
|---|---|---|
$permission | string | The permission string (e.g., rw-r--r--). |
$decimal | int | Whether to return permission as decimal or formatted octal string. |
Return Value:
string|int|null - Return the Unix integer permission, or null if the conversion failed.