Oihana PHP

getTimestampedFile.php

Table of Contents

Functions

getTimestampedFile()  : string|null
Get a timestamped file path using a formatted date and optional prefix/suffix.

Functions

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
throws
FileException

If the file path is invalid.

example
use oihana\files\makeTimestampedFile;
use oihana\enums\Char;

// Example 1: file in the current directory using default format
$file = getTimestampedFile();
// e.g. ./2025-07-15T10:45:33

// Example 2: file inside /tmp with prefix and suffix
$file = getTimestampedFile
(
    date:     '2025-12-01 14:00:00',
    basePath: '/tmp',
    prefix:   'backup_',
    suffix:   '.sql'
);
// e.g. /tmp/backup_2025-12-01T14:00:00.sql

// Example 3: use a different timezone and format
$file = getTimestampedFile
(
    basePath : Char::EMPTY,
    prefix   : 'log_',
    suffix   : '.txt',
    timezone : 'UTC',
    format   : 'Ymd_His'
);
// e.g. ./log_20250715_084533.txt
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
string|null

The full path of the generated file, or null on failure.


        
On this page

Search results