ZetCode

PHP touch 函数

最后修改于 2025 年 4 月 3 日

PHP的touch函数用于修改文件的访问和修改时间。如果文件不存在,它还可以创建空文件。这对于日志记录非常有用。

基本定义

touch函数设置文件的访问和修改时间。如果文件不存在,则可以创建文件。函数成功时返回true。

语法: touch(string $filename, ?int $mtime = null, ?int $atime = null): bool。除文件名外,所有参数都是可选的。时间是Unix时间戳。

基本 touch 示例

这展示了touch更新文件时间戳的最简单用法。

basic_touch.php
<?php

declare(strict_types=1);

$file = "example.txt";

if (touch($file)) {
    echo "Timestamp updated for $file";
} else {
    echo "Failed to update timestamp";
}

这会将访问和修改时间都更新为当前时间。如果文件不存在,它将被创建为空文件。该函数返回一个布尔值结果。

创建新文件

touch可以在文件不存在时创建空文件。

create_file.php
<?php

declare(strict_types=1);

$newFile = "newfile.txt";

if (!file_exists($newFile) && touch($newFile)) {
    echo "Created new empty file: $newFile";
} else {
    echo "File exists or creation failed";
}

这会先检查文件是否存在,然后根据需要创建它。文件将具有当前时间戳和零字节大小。权限取决于umask。

设置特定时间戳

您可以使用可选参数设置自定义时间戳。

custom_timestamps.php
<?php

declare(strict_types=1);

$file = "timestamp.txt";
$time = strtotime("2025-01-01 00:00:00");

if (touch($file, $time)) {
    echo "Set custom timestamp for $file";
    echo "New modification time: " . date("Y-m-d H:i:s", filemtime($file));
}

这会将文件的修改时间设置为2025年1月1日。除非另有指定,否则访问时间也会更新为当前时间。使用Unix时间戳。

同时设置访问和修改时间

您可以独立控制访问和修改时间。

both_timestamps.php
<?php

declare(strict_types=1);

$file = "times.txt";
$mtime = strtotime("2024-06-15 12:00:00");
$atime = strtotime("2024-06-15 08:30:00");

if (touch($file, $mtime, $atime)) {
    echo "Set custom times for $file";
    echo "Modification: " . date("Y-m-d H:i:s", filemtime($file));
    echo "Access: " . date("Y-m-d H:i:s", fileatime($file));
}

这会设置不同的访问和修改时间。第三个参数控制访问时间。两个时间都根据示例中的精确值进行设置。

带错误处理的 Touch

适当的错误处理可以使文件操作更加健壮。

error_handling.php
<?php

declare(strict_types=1);

$file = "/root/protected.txt";

try {
    if (!is_writable(dirname($file))) {
        throw new Exception("Directory not writable");
    }
    
    if (!touch($file)) {
        throw new Exception("Failed to update timestamp");
    }
    
    echo "Timestamp updated successfully";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

这会在尝试操作之前检查目录权限。它使用异常进行错误处理。在处理文件时,请始终验证权限。

最佳实践

来源

PHP touch 文档

本教程通过实际示例介绍了PHP的touch函数,展示了时间戳修改和文件创建。

作者

我叫Jan Bodnar,是一位热情的程序员,拥有丰富的编程经验。我从2007年开始撰写编程文章。迄今为止,我已撰写了1400多篇文章和8本电子书。我在教学编程方面拥有十多年的经验。

列出 所有 PHP 文件系统函数