files
Table of Contents
Namespaces
Functions
- assertDirectory() : void
- Asserts that a directory exists and is accessible, optionally checking readability and writability.
- assertFile() : void
- Asserts that a file exists and meets specified accessibility and MIME type requirements.
- assertWritableDirectory() : void
- Asserts that a directory exists and is readable and writable.
- copyFilteredFiles() : bool
- Recursively copies files and directories from a source to a destination with filtering.
- deleteDirectory() : bool
- Deletes a directory recursively.
- deleteFile() : bool
- Deletes a file from the filesystem.
- deleteTemporaryDirectory() : bool
- Deletes a directory located in the system temporary folder (recursively).
- findFiles() : array<string|int, SplFileInfo>
- Lists files in a directory with advanced filtering, sorting, and recursive options.
- getBaseFileName() : string
- Returns the base file name without its extension from a given file path.
- getDirectory() : string
- Normalises (and optionally validates) a directory path.
- getFileExtension() : string|null
- Retrieves the file extension (including multipart extensions) from a given file path.
- getFileLines() : array<string|int, mixed>|null
- Retrieves all lines from a file as an array, optionally transforming each line with a callback.
- getFileLinesGenerator() : Generator
- Reads a file line by line and yields each line as a generator.
- getHomeDirectory() : string
- Returns the current user’s home directory as a **canonical** path.
- getOwnershipInfos() : OwnershipInfos
- Retrieves the current ownership information of a given file or directory.
- getRoot() : string
- Extracts the root directory component of a given path.
- getSchemeAndHierarchy() : array{0: ?string, 1: string}
- Split a filename or URI into its scheme (if any) and hierarchical part.
- getTemporaryDirectory() : string
- Builds a path inside the system temporary directory.
- getTimestampedDirectory() : string
- Get a timestamped file path using a formatted date and optional prefix/suffix.
- getTimestampedFile() : string|null
- Get a timestamped file path using a formatted date and optional prefix/suffix.
- hasDirectories() : bool
- Checks if a directory contains at least one subdirectory, or only subdirectories if strict mode is enabled.
- hasFiles() : bool
- Checks if a directory contains at least one file, or only files if strict mode is enabled.
- isLinux() : bool
- Indicates if the OS system is Linux.
- isMac() : bool
- Indicates if the OS system is Mac.
- isOtherOS() : bool
- Indicates if the OS system is not Windows, Mac or Linux.
- isWindows() : bool
- Indicates if the OS system is Windows.
- makeDirectory() : string|null
- Creates a directory if it does not exist and returns the path of the directory.
- makeFile() : string
- Creates or updates a file with the given content and options.
- makeTemporaryDirectory() : string
- Creates (or returns if already present) a directory inside the system temporary folder.
- makeTimestampedDirectory() : string|null
- Creates a directory named with a formatted timestamp.
- makeTimestampedFile() : string|null
- Generates a timestamped file path if not exist. Using a formatted date and optional prefix/suffix.
- recursiveFilePaths() : array<string|int, mixed>
- Recursively retrieves all .php files in a folder (and its subfolders).
- requireAndMergeArrays() : array<string|int, mixed>
- Requires multiple PHP files (each returning an array) and merges the results.
- shouldExcludeFile() : bool
- Checks if a file path should be excluded based on an array of patterns.
- sortFiles() : void
- Sorts an array of SplFileInfo objects.
- validateMimeType() : void
- Validate the MIME type of a file against a list of allowed types.
Functions
assertDirectory()
Asserts that a directory exists and is accessible, optionally checking readability and writability.
assertDirectory(string|null $path[, bool $isReadable = true ][, bool $isWritable = false ][, int|null $expectedPermissions = null ]) : void
Parameters
- $path : string|null
-
The path of the directory to check.
- $isReadable : bool = true
-
Whether to assert that the directory is readable. Default: true.
- $isWritable : bool = false
-
Whether to assert that the directory is writable. Default: false.
- $expectedPermissions : int|null = null
-
Optional permission mask (e.g., 0755).
Tags
assertFile()
Asserts that a file exists and meets specified accessibility and MIME type requirements.
assertFile(string|null $file[, array<string|int, mixed>|null $expectedMimeTypes = null ][, bool $isReadable = true ][, bool $isWritable = false ]) : void
This function performs a series of checks on a given file:
- Ensures the file path is not null or empty.
- Confirms that the path points to a valid file.
- Optionally checks if the file is readable.
- Optionally checks if the file is writable.
- Optionally validates the file's MIME type against a provided list.
Parameters
- $file : string|null
-
The path of the file to check. Cannot be null or empty.
- $expectedMimeTypes : array<string|int, mixed>|null = null
-
Optional array of allowed MIME types. If provided, the file's MIME type must match one of these.
- $isReadable : bool = true
-
Whether to assert that the file is readable. Default: true.
- $isWritable : bool = false
-
Whether to assert that the file is writable. Default: false.
Tags
assertWritableDirectory()
Asserts that a directory exists and is readable and writable.
assertWritableDirectory(string|null $directory) : void
Parameters
- $directory : string|null
-
The path of the directory to check.
Tags
copyFilteredFiles()
Recursively copies files and directories from a source to a destination with filtering.
copyFilteredFiles(string $sourceDir, string $destDir[, array<string|int, string> $excludePatterns = [] ][, callable|null $filterCallback = null ]) : bool
This function iterates through a source directory and copies its contents to a destination directory, preserving the folder structure. It provides two methods for filtering which files and directories get copied:
$excludePatterns
: An array of glob/regex patterns. Any file or directory matching a pattern in this array will be skipped. SeeshouldExcludeFile()
.$filterCallback
: An optional user-defined function. This callback receives the full path of each item and must returntrue
for the item to be copied.
Destination directories are created as needed.
Parameters
- $sourceDir : string
-
The path to the source directory to copy from.
- $destDir : string
-
The path to the destination directory.
- $excludePatterns : array<string|int, string> = []
-
An array of patterns to exclude from the copy.
- $filterCallback : callable|null = null
-
Optional callback for custom filtering. It receives the file path and should return
true
to include it.
Tags
Return values
bool —Returns true
if at least one file or directory was copied, false
otherwise.
deleteDirectory()
Deletes a directory recursively.
deleteDirectory(string|array<string|int, mixed>|null $path[, bool $assertable = true ][, bool $isReadable = true ][, bool $isWritable = true ]) : bool
Parameters
- $path : string|array<string|int, mixed>|null
-
Directory or segments to remove.
- $assertable : bool = true
-
Whether to validate the resulting path. Defaults to true.
- $isReadable : bool = true
-
Check if the directory is readable (Default true).
- $isWritable : bool = true
-
Check if the directory is writable (Default false).
Tags
Return values
bool —Returns true if the directory is removed.
deleteFile()
Deletes a file from the filesystem.
deleteFile(string $filePath[, bool $assertable = true ][, bool $isReadable = true ][, bool $isWritable = true ]) : bool
This function optionally asserts that the file exists and meets
the specified readability and writability requirements before attempting deletion.
If the deletion fails, a FileException
is thrown.
Parameters
- $filePath : string
-
The path to the file to delete.
- $assertable : bool = true
-
Whether to perform assertions on the file before deletion (default: true).
- $isReadable : bool = true
-
Whether to assert that the file is readable (default: true).
- $isWritable : bool = true
-
Whether to assert that the file is writable (default: true).
Tags
Return values
bool —Returns true on successful deletion.
deleteTemporaryDirectory()
Deletes a directory located in the system temporary folder (recursively).
deleteTemporaryDirectory(string|array<string|int, string>|null $path[, bool $assertable = true ][, bool $isReadable = true ][, bool $isWritable = true ]) : bool
The given $path
is appended to sys_get_temp_dir()
in the same way as getTemporaryDirectory():
null
→ sys temp dir itself,'logs'
→ "/tmp/logs",['my', 'app']
→ "/tmp/my/app".
Parameters
- $path : string|array<string|int, string>|null
-
Optional sub‑path(s) inside sys_get_temp_dir().
- $assertable : bool = true
-
Whether to validate the composed directory before deletion. Defaults to true.
- $isReadable : bool = true
-
Check readability (passed to assertDirectory()). Defaults to true.
- $isWritable : bool = true
-
Check writability (passed to assertDirectory()). Defaults to true.
Tags
Return values
bool —True if the directory was deleted or did not exist.
findFiles()
Lists files in a directory with advanced filtering, sorting, and recursive options.
findFiles(string|null $directory[, array{filter?: callable|null, followLinks?: bool|null, includeDots?: bool|null, mode?: string|null, order?: string|null, pattern?: string|array|null, recursive?: bool|null, sort?: callable|string|array|null} $options = [] ]) : array<string|int, SplFileInfo>
This function provides flexible options for retrieving files and directories from a given path. It supports recursive search, glob and regex pattern matching, sorting, symbolic link following, and custom filters.
Parameters
- $directory : string|null
-
The target directory path. If null or invalid, a DirectoryException is thrown.
- $options : array{filter?: callable|null, followLinks?: bool|null, includeDots?: bool|null, mode?: string|null, order?: string|null, pattern?: string|array|null, recursive?: bool|null, sort?: callable|string|array|null} = []
-
Optional settings to customize the file listing.
- filter : A function to map or transform each SplFileInfo result.
- followLinks : Whether to follow symbolic links (default: false).
- includeDots : Whether to include dot files (default: false).
- mode : Filter by type: 'files', 'dirs', or 'both' (default: 'files').
- order : Sort order: 'asc' (default) or 'desc'.
- pattern : A glob pattern, regex, or list of patterns to match file names.
- recursive : Whether to search recursively (default: false).
- sort : A sort option, eg: callback, predefined string, or array of keys.
Tags
Return values
array<string|int, SplFileInfo>getBaseFileName()
Returns the base file name without its extension from a given file path.
getBaseFileName(string $file[, array<string|int, mixed>|null $multiplePartExtensions = null ]) : string
This function extracts the file name from a full path and removes its extension.
It supports both single and multi-part extensions (e.g. .tar.gz
, .blade.php
).
Parameters
- $file : string
-
The full path to the file (e.g. '/path/to/archive.tar.gz').
- $multiplePartExtensions : array<string|int, mixed>|null = null
-
Optional list of multi-part extensions to consider (e.g. ['.tar.gz', '.blade.php']). If null, the method defaults to FileExtension::getMultiplePartExtensions().
Tags
Return values
string —The file name without its extension (e.g. 'archive' for 'archive.tar.gz').
getDirectory()
Normalises (and optionally validates) a directory path.
getDirectory(string|array<string|int, mixed>|null $path[, bool $assertable = true ][, bool $isReadable = true ][, bool $isWritable = false ]) : string
- If
$path
is an array, empty segments andChar::EMPTY
are removed, then the remaining parts are joined withDIRECTORY_SEPARATOR
. - If
$assertable
is true (default), assertDirectory() ensures the resulting path exists and is readable. - Trailing separators are always stripped before return.
Parameters
- $path : string|array<string|int, mixed>|null
-
Directory or segments to normalise.
Examples:'/tmp'
or['tmp','logs']
. - $assertable : bool = true
-
Whether to validate the resulting path. Default: true.
- $isReadable : bool = true
-
Whether to assert that the directory is readable. Default: true.
- $isWritable : bool = false
-
Whether to assert that the directory is writable. Default: false.
Tags
Return values
string —Normalized directory path.
getFileExtension()
Retrieves the file extension (including multipart extensions) from a given file path.
getFileExtension(string $file[, array<string|int, mixed>|null $multiplePartExtensions = null ][, bool $lowercase = true ]) : string|null
This function extracts the file extension from the filename portion of the path,
supporting both simple extensions (e.g. .txt
) and multipart extensions (e.g. .tar.gz
, .blade.php
).
It relies on the getBaseFileName()
function to determine the filename without its extension,
then returns the remainder as the extension.
The function normalizes Windows-style backslashes (\
) to forward slashes (/
) before processing.
Parameters
- $file : string
-
The full path or filename from which to extract the extension.
- $multiplePartExtensions : array<string|int, mixed>|null = null
-
Optional array of multipart extensions to consider. If null, the default set from
FileExtension::getMultiplePartExtensions()
is used. - $lowercase : bool = true
-
Enforce the extension to be lowercase (default true).
Tags
Return values
string|null —The file extension including the leading dot (e.g. .tar.gz
),
or null if the file has no extension.
getFileLines()
Retrieves all lines from a file as an array, optionally transforming each line with a callback.
getFileLines(string|null $file[, callable|null $map = null ]) : array<string|int, mixed>|null
This function uses a generator internally (getFileLinesGenerator
) to read the file line by line,
which allows efficient processing of large files. Each line can optionally be mapped using the
provided callable.
Example usage:
use function oihana\files\getFileLines;
$lines = getFileLines('/path/to/file.log');
// Using a mapping function to parse CSV lines
$csvLines = getFileLines('/path/to/data.csv', fn($line) => str_getcsv($line));
Parameters
- $file : string|null
-
The full path to the file to read.
- $map : callable|null = null
-
Optional mapping function applied to each line. Signature: fn(string $line): mixed
Tags
Return values
array<string|int, mixed>|null —Returns an array of lines (or mapped values). Returns an empty array if the file is empty.
getFileLinesGenerator()
Reads a file line by line and yields each line as a generator.
getFileLinesGenerator(string|null $file[, callable|null $map = null ]) : Generator
Each line can optionally be transformed using a callback function. This is particularly useful for processing large files efficiently without loading the entire file into memory at once.
Example usage:
use function oihana\files\getFileLinesGenerator;
// Simply iterate over each line
foreach (getFileLinesGenerator('/path/to/file.log') as $line)
{
echo $line, PHP_EOL;
}
// Using a mapping function to parse CSV lines
foreach (getFileLinesGenerator('/path/to/data.csv', fn($line) => str_getcsv($line)) as $csvRow)
{
print_r($csvRow);
}
Parameters
- $file : string|null
-
Full path to the file to read.
- $map : callable|null = null
-
Optional mapping function applied to each line. Signature: fn(string $line): mixed
Tags
Return values
Generator —Yields each line of the file, optionally transformed by the mapping function.
getHomeDirectory()
Returns the current user’s home directory as a **canonical** path.
getHomeDirectory() : string
Resolution strategy – in order :
- Unix / macOS / Linux
Uses the
HOME
environment variable if it is set and non‑empty. - Windows (≥ XP)
Combines
HOMEDRIVE
+HOMEPATH
(e.g.C:
+\Users\John
) if both are available. - Failure
Throws a
RuntimeException
when no recognised combination is found.
The resulting string is passed through canonicalizePath() so that path separators are normalized (backslashes → slashes) and redundant slashes are removed.
Tags
Return values
string —Canonical absolute path to the user’s home directory.
getOwnershipInfos()
Retrieves the current ownership information of a given file or directory.
getOwnershipInfos(string $path) : OwnershipInfos
Returns an OwnershipInfo
object containing both numeric UID/GID and
their corresponding human-readable owner and group names (if resolvable).
Requires the posix
extension to resolve usernames and group names;
otherwise, owner
and group
may be null
.
Parameters
- $path : string
-
Absolute or relative path to the file or directory.
Tags
Return values
OwnershipInfos —Object containing UID, GID, and optionally owner and group names.
getRoot()
Extracts the root directory component of a given path.
getRoot(string $path) : string
This function identifies the root portion of a file system path, including handling of protocol schemes. ( e.g., "file://", "s3://" )
UNIX root ("/"), and Windows root ( e.g., "C:/" ).
It returns the canonical root as a string, or an empty string if the path is relative or empty.
Behavior:
"file:///usr/bin"
→"file:///"
"/usr/bin"
→"/"
"C:\\Windows\\System32"
→"C:/"
"relative/path"
→""
(empty string)
Parameters
- $path : string
-
The input path, optionally with a scheme.
Tags
Return values
string —The root component of the path, or an empty string if no root can be determined.
getSchemeAndHierarchy()
Split a filename or URI into its scheme (if any) and hierarchical part.
getSchemeAndHierarchy(string $filename) : array{0: ?string, 1: string}
Logic
- Detect the first “://” only once – no array allocation if not present.
- Accept schemes that match RFC‑3986
[A‑Za‑z][A‑Za‑z0‑9+\-.]*
. - Return
[$scheme, $hierarchy]
, where$scheme
isnull
when absent.
Parameters
- $filename : string
-
A path or URI such as
file:///tmp/app.log
or/etc/hosts
.
Tags
Return values
array{0: ?string, 1: string}getTemporaryDirectory()
Builds a path inside the system temporary directory.
getTemporaryDirectory([string|array<string|int, string>|null $path = null ][, bool $assertable = false ][, bool $isReadable = true ][, bool $isWritable = false ]) : string
Parameters
- $path : string|array<string|int, string>|null = null
-
Optional sub‑path(s) to append inside sys_get_temp_dir().
- $assertable : bool = false
-
Whether to validate the final directory path. Defaults to false because the directory may not exist yet.
- $isReadable : bool = true
-
Check if the directory is readable (Default true).
- $isWritable : bool = false
-
Check if the directory is writable (Default false).
Tags
Return values
string —Normalised temporary directory path.
getTimestampedDirectory()
Get a timestamped file path using a formatted date and optional prefix/suffix.
getTimestampedDirectory([string|null $date = null ][, string $basePath = Char::EMPTY ][, string $prefix = Char::EMPTY ][, string $suffix = Char::EMPTY ][, string|null $timezone = 'Europe/Paris' ][, string|null $format = 'Y-m-dTH:i:s' ][, bool $assertable = true ]) : string
Combines a date/time string (or the current time) with optional *extension, prefix, suffix, and base path to generate a unique file name. The file is not created on disk.
Asserts by default if the file exist, you can disabled the behavior with the boolean assertable argument.
Parameters
- $date : string|null = null
-
Optional date/time string to use. If null or invalid, the current date/time is used ("now").
- $basePath : string = Char::EMPTY
-
Optional base path in which to place the directory. Defaults to the current directory.
- $prefix : string = Char::EMPTY
-
Optional string to prepend to the directory name (e.g., "/hello-2025-12-01T14:00:00"").
- $suffix : string = Char::EMPTY
-
Optional string to append to the directory name (e.g., "/2025-12-01T14:00:00-hello"").
- $timezone : string|null = 'Europe/Paris'
-
Timezone identifier (e.g., 'Europe/Paris'). Defaults to 'Europe/Paris'.
- $format : string|null = 'Y-m-dTH:i:s'
-
Date format compatible with DateTime::format(). Defaults to 'Y-m-d\TH:i:s'.
- $assertable : bool = true
-
Whether to validate the path with assertDirectory(). Defaults to true.
Tags
Return values
string —The full path of the generated directory.
getTimestampedFile()
Get a timestamped file path using a formatted date and optional prefix/suffix.
getTimestampedFile([string|null $date = null ][, string $basePath = Char::EMPTY ][, string|null $extension = null ][, string $prefix = Char::EMPTY ][, string $suffix = Char::EMPTY ][, string|null $timezone = 'Europe/Paris' ][, string|null $format = 'Y-m-dTH:i:s' ][, bool $assertable = true ]) : string|null
Combines a date/time string (or the current time) with optional *extension, prefix, suffix, and base path to generate a unique file name. The file is not created on disk.
Asserts by default if the file exist, you can disabled the behavior with the boolean assertable argument.
Parameters
- $date : string|null = null
-
Optional date/time string to use. If null or invalid, the current date/time is used ("now").
- $basePath : string = Char::EMPTY
-
Optional base path in which to place the file. Defaults to the current directory.
- $extension : string|null = null
-
Optional extension to append to the file name (e.g., ".log", ".txt").
- $prefix : string = Char::EMPTY
-
Optional string to prepend to the file name.
- $suffix : string = Char::EMPTY
-
Optional string to append to the file name (e.g., "2025-12-01T14:00:00-hello"").
- $timezone : string|null = 'Europe/Paris'
-
Timezone identifier (e.g., 'Europe/Paris'). Defaults to 'Europe/Paris'.
- $format : string|null = 'Y-m-dTH:i:s'
-
Date format compatible with DateTime::format(). Defaults to 'Y-m-d\TH:i:s'.
- $assertable : bool = true
-
Whether to validate the path with assertFile(). Defaults to true.
Tags
Return values
string|null —The full path of the generated file, or null on failure.
hasDirectories()
Checks if a directory contains at least one subdirectory, or only subdirectories if strict mode is enabled.
hasDirectories(string|null $dir[, bool $strict = false ]) : bool
Parameters
- $dir : string|null
-
The path to the directory to check. Must be a valid readable directory.
- $strict : bool = false
-
If true, the function returns true only if the directory contains only subdirectories (no files or other items). Defaults to false.
Tags
Return values
bool —Returns true if the directory contains at least one subdirectory, or if in strict mode, only subdirectories.
hasFiles()
Checks if a directory contains at least one file, or only files if strict mode is enabled.
hasFiles(string|null $dir[, bool $strict = false ]) : bool
Parameters
- $dir : string|null
-
The path to the directory to check. Must be a valid readable directory.
- $strict : bool = false
-
If true, the function returns true only if the directory contains only files (no directories or other items). Defaults to false.
Tags
Return values
bool —Returns true if the directory contains at least one file, or if in strict mode, only files.
isLinux()
Indicates if the OS system is Linux.
isLinux() : bool
Tags
Return values
boolisMac()
Indicates if the OS system is Mac.
isMac() : bool
Tags
Return values
boolisOtherOS()
Indicates if the OS system is not Windows, Mac or Linux.
isOtherOS() : bool
Tags
Return values
boolisWindows()
Indicates if the OS system is Windows.
isWindows() : bool
Tags
Return values
boolmakeDirectory()
Creates a directory if it does not exist and returns the path of the directory.
makeDirectory(null|array<string|int, mixed>|string $pathOrOptions[, int $permissions = 0755 ][, bool $recursive = true ][, string|null $owner = null ][, string|null $group = null ]) : string|null
Parameters
- $pathOrOptions : null|array<string|int, mixed>|string
-
The path of the directory to create.
- $permissions : int = 0755
-
The permissions to set for the directory (default: 0755).
- $recursive : bool = true
-
If true, creates parent directories as needed (default: true).
- $owner : string|null = null
-
User name or ID to set as directory owner (optional).
- $group : string|null = null
-
Group name or ID to set as directory group (optional).
Tags
Return values
string|null —Returns the path of the directory.
makeFile()
Creates or updates a file with the given content and options.
makeFile(array{append?: bool, content?: string|null, file?: string|null, force?: bool, group?: null|string, lock?: bool, overwrite?: bool, permissions?: int, owner?: string|null}|string|null $fileOrOptions[, string|null $content = null ][, array{append?: bool, force?: bool, group?: null|string, lock?: bool, overwrite?: bool, permissions?: int, owner?: string|null} $options = [] ]) : string
This function writes content to the specified file path. It supports appending to existing files, overwriting, setting file permissions, changing ownership, and group. It can also create the parent directories if needed.
Usage:
- Classic signature:
makeFile(string $filePath, string $content = '', array $options = []);
- Signature with options array as first parameter:
makeFile(array $options);
Required keys in $options:
- 'filePath' (string): The path of the file to create or modify (mandatory).
- 'content' (string): The content to write into the file (optional, default ''). Other keys correspond to options (see below).
Parameters
- $fileOrOptions : array{append?: bool, content?: string|null, file?: string|null, force?: bool, group?: null|string, lock?: bool, overwrite?: bool, permissions?: int, owner?: string|null}|string|null
-
Either the file path as a string (classic usage), or an associative array containing at least 'filePath' and optionally 'content' and other options.
- $content : string|null = null
-
The content to write into the file. Defaults to empty string. Ignored if $filePathOrOptions is array.
- $options : array{append?: bool, force?: bool, group?: null|string, lock?: bool, overwrite?: bool, permissions?: int, owner?: string|null} = []
-
An associative array of options:
- 'append' (bool): If true, appends content instead of overwriting. Default: false.
- 'force' (bool): If true, creates parent directories if they do not exist. Default: true.
- 'group' (string|null): Group name or ID to set as file group owner. Default: null.
- 'lock' (bool): If true, uses an exclusive lock while writing. Default: true.
- 'overwrite' (bool): If true, overwrites existing files. Default: false.
- 'permissions' (int): File permissions to set (octal). Default: 0644.
- 'owner' (string|null): User name or ID to set as file owner. Default: null.
Tags
Return values
string —The path of the created or updated file.
makeTemporaryDirectory()
Creates (or returns if already present) a directory inside the system temporary folder.
makeTemporaryDirectory(string|array<string|int, string>|null $path[, int $permission = 0755 ]) : string
The sub‑path is appended to sys_get_temp_dir()
de la même manière que
getTemporaryDirectory() :
null
→ the temp dir itself'cache'
→/tmp/cache
['my', 'app']
→/tmp/my/app
Parameters
- $path : string|array<string|int, string>|null
-
Optional sub‑directory path segments.
- $permission : int = 0755
-
Octal mode for
mkdir()
(default:0755
).
Tags
Return values
string —Full path to the (existing or newly created) temporary directory.
makeTimestampedDirectory()
Creates a directory named with a formatted timestamp.
makeTimestampedDirectory([string|null $date = null ][, string $basePath = Char::EMPTY ][, string $prefix = Char::EMPTY ][, string $suffix = Char::EMPTY ][, string|null $timezone = 'Europe/Paris' ][, string|null $format = 'Y-m-dTH:i:s' ]) : string|null
Combines a date/time string (or the current time) with optional prefix, suffix, and base path to generate a unique directory name. The directory is created if it does not already exist.
Parameters
- $date : string|null = null
-
Optional date/time string to use. If null or invalid, the current date/time is used ("now").
- $basePath : string = Char::EMPTY
-
Optional base path in which to create the directory. Defaults to an empty string.
- $prefix : string = Char::EMPTY
-
Optional string to prepend to the directory name.
- $suffix : string = Char::EMPTY
-
Optional string to append to the directory name.
- $timezone : string|null = 'Europe/Paris'
-
Timezone identifier (e.g., 'Europe/Paris'). Defaults to 'Europe/Paris'.
- $format : string|null = 'Y-m-dTH:i:s'
-
Date format compatible with DateTime::format(). Defaults to 'Y-m-d\TH:i:s'.
Tags
Return values
string|null —The full path of the created directory, or null on failure.
makeTimestampedFile()
Generates a timestamped file path if not exist. Using a formatted date and optional prefix/suffix.
makeTimestampedFile([string|null $date = null ][, string $basePath = Char::EMPTY ][, string|null $extension = null ][, string $prefix = Char::EMPTY ][, string $suffix = Char::EMPTY ][, string|null $timezone = 'Europe/Paris' ][, string|null $format = 'Y-m-dTH:i:s' ][, bool $mustExist = false ]) : string|null
Combines a date/time string (or the current time) with optional prefix, suffix, and base path to generate a unique file name. The file is not created on disk.
Parameters
- $date : string|null = null
-
Optional date/time string to use. If null or invalid, the current date/time is used ("now").
- $basePath : string = Char::EMPTY
-
Optional base path in which to place the file. Defaults to the current directory.
- $extension : string|null = null
-
Optional extension to append to the file name (e.g., ".log", ".txt").
- $prefix : string = Char::EMPTY
-
Optional string to prepend to the file name.
- $suffix : string = Char::EMPTY
-
Optional string to append to the file name (e.g., "2025-12-01T14:00:00-hello"").
- $timezone : string|null = 'Europe/Paris'
-
Timezone identifier (e.g., 'Europe/Paris'). Defaults to 'Europe/Paris'.
- $format : string|null = 'Y-m-dTH:i:s'
-
Date format compatible with DateTime::format(). Defaults to 'Y-m-d\TH:i:s'.
- $mustExist : bool = false
-
Whether the generated file must exist. If true, asserts the file exists. Defaults to false.
Tags
Return values
string|null —The full path of the generated file, or null on failure.
recursiveFilePaths()
Recursively retrieves all .php files in a folder (and its subfolders).
recursiveFilePaths(string $directory[, array{excludes?: array|null, extensions?: array|null, maxDepth?: int, sortable?: bool} $options = [] ]) : array<string|int, mixed>
Parameters
- $directory : string
-
The base path of the file to be scanned.
- $options : array{excludes?: array|null, extensions?: array|null, maxDepth?: int, sortable?: bool} = []
-
The optional parameter to send in the function.
- excludes (array) : The enumeration of all files to excludes
- extensions (array) : The optional list of the extensions to use to scan the folder(s).
- maxDepth (int) : The maximum allowed depth. Default -1 is used
- sortable (bool) : Indicates if the list of file paths is sorted before returned.
Tags
Return values
array<string|int, mixed> —The list of the full paths to all files found.
requireAndMergeArrays()
Requires multiple PHP files (each returning an array) and merges the results.
requireAndMergeArrays(array<string|int, mixed> $filePaths[, bool $recursive = true ]) : array<string|int, mixed>
Parameters
- $filePaths : array<string|int, mixed>
-
An array of absolute or relative file paths to load.
- $recursive : bool = true
-
Whether to perform a deep (recursive) merge (true) or a simple merge (false).
Tags
Return values
array<string|int, mixed> —The merged array.
shouldExcludeFile()
Checks if a file path should be excluded based on an array of patterns.
shouldExcludeFile(string $filePath, array<string|int, string> $excludePatterns) : bool
This function supports two types of patterns:
- Glob patterns (e.g., '.log', 'config/.php'). These are matched using fnmatch().
- PCRE regular expressions (e.g., '/^temp-\d+.tmp$/i'). The function auto-detects regex patterns by checking if they are enclosed in matching delimiter characters.
For each pattern, the function attempts to match it against both the full file path and the basename of the file. The match is successful if any pattern matches. The glob matching is performed with the FNM_PATHNAME flag, meaning wildcards will not match directory separators (/).
Parameters
- $filePath : string
-
The absolute or relative path to the file to check.
- $excludePatterns : array<string|int, string>
-
An array of glob or PCRE patterns.
Tags
Return values
bool —Returns true
if the file path matches any of the exclusion patterns, false
otherwise.
sortFiles()
Sorts an array of SplFileInfo objects.
sortFiles(array<string|int, SplFileInfo> &$files, callable|string|array<string|int, mixed> $sort[, string|null $order = 'asc' ]) : void
Parameters
- $files : array<string|int, SplFileInfo>
-
Array of files to sort (modified in‑place).
- $sort : callable|string|array<string|int, mixed>
-
One of:
- callable : custom compare function, ex:
fn(SplFileInfo $a, SplFileInfo $b): int
- string : single built‑in key
'name' | 'ci_name' | 'extension' | 'size' | 'type' | 'atime' | 'ctime' | 'mtime'
- array : ordered list of such keys for multi‑criteria sorting e.g. ['type', 'name'] or ['extension','size']
- callable : custom compare function, ex:
- $order : string|null = 'asc'
-
The direction of the sort method 'asc' (default) or 'desc'.
Tags
validateMimeType()
Validate the MIME type of a file against a list of allowed types.
validateMimeType(string $file, array<string|int, mixed> $allowedMimeTypes) : void
Parameters
- $file : string
-
Path to the file to validate.
- $allowedMimeTypes : array<string|int, mixed>
-
List of allowed MIME types. Can include strings or arrays of strings.