Oihana PHP

makeTimestampedFile.php

Table of Contents

Functions

makeTimestampedFile()  : string|null
Generates a timestamped file path if not exist. Using a formatted date and optional prefix/suffix.

Functions

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

If the file path is invalid, not writable, or must exist but does not.

example
use oihana\files\makeTimestampedFile;

// Example 1: Generate a file path with current datetime in default format, no prefix/suffix
$filePath = makeTimestampedFile();
// e.g. "./2025-07-15T10:45:33"

// Example 2: Generate a file path with a specific date and extension inside /tmp
$filePath = makeTimestampedFile(
    date: '2025-12-01 14:00:00',
    basePath: '/tmp',
    extension: '.log'
);
// e.g. "/tmp/2025-12-01T14:00:00.log"

// Example 3: Add prefix and suffix, use a custom timezone and date format
$filePath = makeTimestampedFile(
    prefix: 'backup_',
    suffix: '_final',
    timezone: 'UTC',
    format: 'Ymd_His'
);
// e.g. "./backup_20250715_084533_final"

// Example 4: Require that the generated file already exists (throws if not)
$filePath = makeTimestampedFile(mustExist: true);
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