Skip to content
← Back to Snippets
Code

Get a File's Last Modified Time

Returns a readable last-modified timestamp for a file after confirming the file resolves under an approved base directory.

Purpose

Returns a readable last-modified timestamp for a file after confirming the file resolves under an approved base directory.

Snippet details

ContextFile SystemLevelPracticalCopy-and-paste statusMarked safe after review.

Categories

  • Forms and Validation

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Get a File's Last Modified Time.
 *
 * Purpose:
 * Reads filemtime() only for files under an approved directory.
 *
 * @param string $file_path Candidate file path.
 * @param string $base_dir Approved base directory.
 * @param string $timezone_name Display timezone.
 * @return array Modified-time result.
 */
function ogSnippetGetFileModifiedTime(string $file_path, string $base_dir, string $timezone_name): array {
	$result = array(
		'ok' => false,
		'timestamp' => 0,
		'display' => '',
		'message' => 'File modified time was not read.'
	);

	$resolved_base = realpath($base_dir);
	$resolved_file = realpath($file_path);

	if ($resolved_base === false || $resolved_file === false) {
		$result['message'] = 'File path could not be resolved.';
		return $result;
	}

	if (strpos($resolved_file, $resolved_base) !== 0) {
		$result['message'] = 'File is outside the approved directory.';
		return $result;
	}

	if (is_file($resolved_file) === false || is_readable($resolved_file) === false) {
		$result['message'] = 'File is not readable.';
		return $result;
	}

	$timestamp = filemtime($resolved_file);

	if ($timestamp === false) {
		return $result;
	}

	if (in_array($timezone_name, timezone_identifiers_list(), true) === false) {
		$timezone_name = 'UTC';
	}

	$timezone = new DateTimeZone($timezone_name);
	$modified_time = new DateTimeImmutable('@'.$timestamp);
	$modified_time = $modified_time->setTimezone($timezone);

	$result['ok'] = true;
	$result['timestamp'] = $timestamp;
	$result['display'] = $modified_time->format('F j, Y g:i A T');
	$result['message'] = 'File modified time was read.';

	return $result;
}

$modified_report = ogSnippetGetFileModifiedTime(__FILE__, __DIR__, 'America/New_York');

echo 'File modified: '.$modified_report['display'];