ZetCode

PHP filectime 函数

最后修改于 2025 年 4 月 3 日

PHP 的 filectime 函数返回文件的创建时间。这与修改时间和访问时间不同。它对于文件管理任务很有用。

基本定义

filectime 函数返回文件创建时的 Unix 时间戳。在 Unix 系统上,这是 inode 更改时间。在 Windows 上,这是实际的创建时间。

语法:filectime(string $filename): int|false。成功时返回时间戳,失败时返回 false。时间戳可以使用日期函数格式化。

基本的 filectime 示例

这展示了 filectime 的最简单用法,以获取创建时间。

basic_filectime.php
<?php

declare(strict_types=1);

$filename = "example.txt";
$ctime = filectime($filename);

echo "File created on: " . date("Y-m-d H:i:s", $ctime);

这以可读的格式输出创建时间。 date 函数将 Unix 时间戳转换为人类可读的字符串。

首先检查文件是否存在

在获取文件的 ctime 之前检查文件是否存在是一个好习惯。

filectime_exists.php
<?php

declare(strict_types=1);

$filename = "example.txt";

if (file_exists($filename)) {
    $ctime = filectime($filename);
    echo "File created: " . date("Y-m-d", $ctime);
} else {
    echo "File does not exist";
}

如果文件不存在,这可以防止出现警告。 file_exists 检查确保我们只在现有文件上调用 filectime

与 Filemtime 比较

此示例显示了创建时间和修改时间之间的区别。

filectime_vs_filemtime.php
<?php

declare(strict_types=1);

$filename = "example.txt";

$ctime = filectime($filename);
$mtime = filemtime($filename);

echo "Created: " . date("Y-m-d H:i:s", $ctime) . "\n";
echo "Modified: " . date("Y-m-d H:i:s", $mtime);

创建时间保持不变,而修改时间在内容更新时会发生变化。这有助于跟踪文件首次创建的时间与最后一次更改的时间。

处理目录

filectime 同样适用于目录和文件。

directory_ctime.php
<?php

declare(strict_types=1);

$dir = "documents";

$ctime = filectime($dir);

echo "Directory created: " . date("Y-m-d", $ctime);

这显示了目录的创建时间。该函数对于目录的行为与对于普通文件的行为相同。

错误处理

适当的错误处理使代码在处理文件系统操作时更加健壮。

filectime_error.php
<?php

declare(strict_types=1);

$filename = "nonexistent.txt";

$ctime = @filectime($filename);

if ($ctime === false) {
    echo "Could not get creation time";
} else {
    echo "Created: " . date("Y-m-d", $ctime);
}

@ 运算符抑制警告,并且我们显式地检查返回值。这比让 PHP 发出警告提供了更清晰的错误处理。

最佳实践

来源

PHP filectime 文档

本教程通过实际示例介绍了 PHP filectime 函数,展示了它在不同场景中的用法。

作者

我的名字是 Jan Bodnar,我是一位充满激情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

列出 所有 PHP 文件系统函数