Luminova Framework

PHP Luminova: Filesystem Operations

Last updated: 2026-01-25 19:04:45

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 owner

You can also call any SplFileInfo method:

echo $fs->getFilename(); // Same as $fs->filename

Reading 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 50

Writing 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 $position after 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.";

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 size

Working with Permissions

Convert numeric permission to string

echo Filesystem::permissions(0755); // Output: rwxr-xr-x

Convert string permission to Unix number

echo Filesystem::toUnixPermission('rw-r--r--'); // Output: 0644

Set 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 $system

plugins

Path to the system third-party plugins.

protected string $plugins

library

Path to the libraries and third-party modules.

protected string $library

services

Path to the serialized shared services.

protected string $services

controllers

Path to the application controllers.

protected string $controllers

writeable

Path to the writeable files.

protected string $writeable

logs

Path to the error logs.

protected string $logs

caches

Path to the application caches.

protected string $caches

public

Path to the public controller document root.

protected string $public

assets

Path to the public assets directory.

protected string $assets

views

Path to the template views files.

protected string $views

routes

Path to the application routes.

protected string $routes

languages

Path to the languages modules.

protected string $languages

Methods

setPermission

Set permissions for a file or directory.

public static setPermission(string $location, int $permission): bool

Parameters:

ParameterTypeDescription
$locationstringThe path to the file or directory.
$permissionintThe 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): string

Parameters:

ParameterTypeDescription
$permissionintThe 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
): bool

Parameters:

ParameterTypeDescription
$filenamestringPath to the file to write.
$contentstring|resourceThe data to write, either as a string or a stream resource.
$flagsintOptional file flags (e.g., FILE_APPEND, FILE_USE_INCLUDE_PATH, LOCK_EX).
$retriesintNumber of times to retry acquiring the lock in non-blocking mode.
$delayintDelay in microseconds between retries (default 50_000 = 50ms)..
$contextresource|nullOptional stream context created via stream_context_create().
&$bytesintThe number of bytes written, or 0 on error.

Return Value:

bool - Returns true if writing succeeds, false otherwise.

Throws:

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): bool

Parameters:

ParameterTypeDescription
$pathstringThe directory path to create.
$permissionsintUnix file permissions (default: 0777, fully accessible to all users).
$recursiveboolWhether 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): bool

Parameters:

ParameterTypeDescription
$originstringThe source directory or file path to copy.
$deststringThe destination directory path.
$skipIfExistsboolWether to skip already existing files or directories (default: false).
$copiedintReference 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:


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): bool

Parameters:

ParameterTypeDescription
$originstringThe source directory or file path to move.
$deststringThe destination directory path.
$skipIfExistsboolWether to skip already existing files or directories (default: false).
$movedintReference 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:


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): int

Parameters:

ParameterTypeDescription
$sourcemixedFile 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
): bool

Parameters:

ParameterTypeDescription
$sourceresource|stringFile stream or file path.
$filesizeint|nullOptional known file size in bytes, auto-detected if null (default: null).
$mimeLuminova\Utility\MIME|string|nullOptional MIME type for content detection.
Used to determine read method.
$lengthintMaximum read chunk size in bytes (default: 2MB).
$delayintDelay in microseconds between chunk reads.
&$positionintStarting position in the file; updated to final read position (default: 0).
$nonBlockingboolIf 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
): bool

Parameters:

ParameterTypeDescription
$contentstring|resourceThe full file path, resource, or string to download.
$filenamestring|nullThe filename as it will be shown in the download (e.g, image.png).
$headersarray<string,mixed>Optional array headers for download..
$deleteboolWhether to delete the file after download (default: false).
$chunk_sizeintThe size of each chunk in bytes for large content (default: 8192, 8KB).
$delayintThe 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): int

Parameters:

ParameterTypeDescription
$locationstringDirectory or file to delete.
$delete_baseboolRemove the base directory once done (default is false).
$deletedintReference 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): bool

Parameters:

ParameterTypeDescription
$targetstringThe targe file or directory to link from.
$linkstringThe 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): bool

Parameters:

ParameterTypeDescription
$resourcemixedThe resource to check.
$typestringThe 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): bool

Parameters:

ParameterTypeDescription
$pathstringThe 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): bool

Parameters:

ParameterTypeDescription
$pathstringThe 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|null

Parameters:

ParameterTypeDescription
$permissionstringThe permission string (e.g., rw-r--r--).
$decimalintWhether 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.