ZetCode

PHP fopen 函数

最后修改于 2025 年 4 月 3 日

PHP 的 fopen 函数用于打开文件或 URL 以进行读取或写入。它是 PHP 应用程序中文件处理操作的基础。

基本定义

fopen 函数创建一个文件指针资源,连接到指定的文件或 URL。它需要一个文件名和模式参数。

语法:fopen(string $filename, string $mode, bool $use_include_path = false, ?resource $context = null): resource|false

该函数在成功时返回一个文件指针资源,失败时返回 false。在进行文件操作之前,务必检查返回值。

以读取模式打开文件

此示例演示了以只读模式打开文件。

read_file.php
<?php

declare(strict_types=1);

$filename = "example.txt";
$handle = fopen($filename, "r");

if ($handle === false) {
    throw new RuntimeException("Failed to open file: {$filename}");
}

// Read and process the file here
fclose($handle);

"r" 模式仅用于读取。 我们在继续操作之前检查操作是否成功。完成操作后,务必使用 fclose 关闭文件。

创建和写入文件

此示例演示了如何创建新文件并将内容写入其中。

write_file.php
<?php

declare(strict_types=1);

$filename = "output.txt";
$handle = fopen($filename, "w");

if ($handle === false) {
    throw new RuntimeException("Failed to create file: {$filename}");
}

$bytes = fwrite($handle, "Hello, World!\n");
if ($bytes === false) {
    throw new RuntimeException("Failed to write to file");
}

fclose($handle);

"w" 模式创建文件(如果不存在),或者将其截断为零长度(如果存在)。我们写入一个字符串并检查返回值。

追加到文件

此示例演示了如何将内容追加到现有文件。

append_file.php
<?php

declare(strict_types=1);

$filename = "log.txt";
$handle = fopen($filename, "a");

if ($handle === false) {
    throw new RuntimeException("Failed to open file for appending: {$filename}");
}

$logEntry = date('Y-m-d H:i:s') . " - User logged in\n";
$bytes = fwrite($handle, $logEntry);
if ($bytes === false) {
    throw new RuntimeException("Failed to append to file");
}

fclose($handle);

"a" 模式仅用于写入,将指针置于文件末尾。 这对于日志文件和类似用例非常理想。

同时读写

此示例演示了如何打开文件以进行读写。

read_write_file.php
<?php

declare(strict_types=1);

$filename = "data.txt";
$handle = fopen($filename, "r+");

if ($handle === false) {
    throw new RuntimeException("Failed to open file for read/write: {$filename}");
}

$content = fread($handle, filesize($filename));
if ($content === false) {
    throw new RuntimeException("Failed to read file");
}

// Modify content
$newContent = strtoupper($content);

rewind($handle);
$bytes = fwrite($handle, $newContent);
if ($bytes === false) {
    throw new RuntimeException("Failed to write to file");
}

fclose($handle);

"r+" 模式用于读写。 我们读取内容,修改它,然后在倒回指针后将其写回。

使用远程文件

此示例演示了如何使用 HTTP 打开远程文件。

remote_file.php
<?php

declare(strict_types=1);

$url = "https://example.com/data.json";
$handle = fopen($url, "r");

if ($handle === false) {
    throw new RuntimeException("Failed to open remote file: {$url}");
}

$content = stream_get_contents($handle);
if ($content === false) {
    throw new RuntimeException("Failed to read remote file");
}

// Process the remote content
$data = json_decode($content, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    throw new RuntimeException("JSON decode error: " . json_last_error_msg());
}

fclose($handle);

当 php.ini 中启用了 allow_url_fopen 时,fopen 可以打开 URL。在此示例中,我们读取远程内容并将其作为 JSON 处理。

最佳实践

来源

PHP fopen 文档

本教程涵盖了 PHP 的 fopen 函数,并附有实际示例,展示了各种文件打开模式和用例。

作者

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

列出 所有 PHP 文件系统函数