导航菜单

PHP/文件与异常处理
课程进度 33% · 第8/22章8/22章 · 标签 1/4
1

文件操作基础

PHP通过内置函数进行文件操作,如fopen、fclose、fread、fwrite等。常用模式:r(只读)、w(只写)、a(追加)、r+(读写)。文件操作前建议判断文件是否存在:file_exists。

php
1
<?php
2
// 检查文件是否存在
3
if (file_exists("test.txt")) {
4
echo "文件存在";
5
} else {
6
echo "文件不存在";
7
}
8
 
9
// 打开文件(只读)
10
$handle = fopen("test.txt", "r");
11
if ($handle) {
12
// 关闭文件
13
fclose($handle);
14
}
15
?>
2

文件读写

读取文件内容:fread、file_get_contents。写入文件内容:fwrite、file_put_contents。逐行读取:fgets。文件指针操作:feof、rewind。

php
1
<?php
2
// 读取整个文件内容
3
$content = file_get_contents("test.txt");
4
echo $content;
5
 
6
// 逐行读取文件
7
$handle = fopen("test.txt", "r");
8
if ($handle) {
9
while (($line = fgets($handle)) !== false) {
10
echo $line;
11
}
12
fclose($handle);
13
}
14
 
15
// 写入文件
16
$handle = fopen("test.txt", "w");
17
if ($handle) {
18
fwrite($handle, "Hello, world!\n");
19
fclose($handle);
20
}
21
 
22
// 追加内容
23
file_put_contents("test.txt", "追加内容\n", FILE_APPEND);
24
?>
file_get_contentsfopenfwritefgetsfeof