ZetCode

PHP tmpfile 函数

最后修改于 2025 年 4 月 3 日

PHP 的 tmpfile 函数以读写 (w+) 模式创建一个具有唯一名称的临时文件。当文件被关闭或脚本结束时,该文件将自动删除。

基本定义

tmpfile 函数创建一个临时文件并返回一个文件句柄。该文件在系统的临时目录中创建,名称是唯一的。

语法:tmpfile(): resource|false。成功时返回文件句柄,失败时返回 false。当调用 fclose() 或脚本结束时,该文件将被删除。

基本 tmpfile 示例

这展示了使用 tmpfile 创建临时文件的最简单用法。

basic_tmpfile.php
<?php

declare(strict_types=1);

$tempFile = tmpfile();

if ($tempFile === false) {
    die("Failed to create temporary file");
}

fwrite($tempFile, "Hello, temporary file!");
rewind($tempFile);
echo fread($tempFile, 1024);

fclose($tempFile); // File is automatically deleted

这创建了一个临时文件,向其中写入内容,读回内容,然后关闭它。当调用 fclose() 或脚本终止时,该文件将被删除。

写入结构化数据

临时文件可以存储结构化数据,如 JSON 或序列化的 PHP 数据。

structured_data.php
<?php

declare(strict_types=1);

$tempFile = tmpfile();
$data = ['name' => 'John', 'age' => 30, 'city' => 'New York'];

fwrite($tempFile, json_encode($data));
rewind($tempFile);

$content = fread($tempFile, 1024);
$decoded = json_decode($content, true);

print_r($decoded);
fclose($tempFile);

此示例将一个数组存储为 JSON 格式的临时文件,然后将其读回。临时文件对于中间数据处理非常有用,无需永久存储。

流操作

临时文件支持所有标准流操作,如 fseek 和 ftell。

stream_operations.php
<?php

declare(strict_types=1);

$tempFile = tmpfile();
fwrite($tempFile, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");

fseek($tempFile, 10, SEEK_SET);
echo fread($tempFile, 5); // Outputs: KLMNO

echo "\nCurrent position: " . ftell($tempFile); // 15
fclose($tempFile);

这演示了在临时文件中进行 seek 操作和从特定位置读取内容。可以使用 ftell() 跟踪文件指针位置。

错误处理

在使用临时文件时,适当的错误处理非常重要。

error_handling.php
<?php

declare(strict_types=1);

$tempFile = @tmpfile();

if ($tempFile === false) {
    $error = error_get_last();
    echo "Error creating temp file: " . $error['message'];
    exit(1);
}

try {
    if (fwrite($tempFile, "Test data") === false) {
        throw new RuntimeException("Write failed");
    }
    // Process file...
} finally {
    if (is_resource($tempFile)) {
        fclose($tempFile);
    }
}

这展示了针对临时文件创建和操作的强大错误处理。 finally 块确保即使发生错误,文件也能被正确关闭。

多个临时文件

你可以在单个脚本中创建和管理多个临时文件。

multiple_files.php
<?php

declare(strict_types=1);

$file1 = tmpfile();
$file2 = tmpfile();

fwrite($file1, "Data for file 1");
fwrite($file2, "Data for file 2");

rewind($file1);
rewind($file2);

echo "File 1: " . fread($file1, 1024) . "\n";
echo "File 2: " . fread($file2, 1024) . "\n";

fclose($file1);
fclose($file2);

这创建了两个具有不同内容的独立临时文件。每个临时文件都有一个唯一的名称,可以在自动删除之前单独管理。

最佳实践

来源

PHP tmpfile 文档

本教程介绍了 PHP 的 tmpfile 函数,并提供了实用示例,展示了其在临时数据存储和处理中的用法。

作者

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

列出 所有 PHP 文件系统函数