file_get_contents(
string $filename,
bool $use_include_path = false,
?resource $context = null,
int $offset = 0,
?int $length = null
): string|false
$fileName = 'test.txt';
if (file_exists($fileName)) {
$str = file_get_contents($fileName);
echo $str;
} else {
print_r("文件不存在");
}
file(string $filename, int $flags = 0, ?resource $context = null): array|false
$lines = file('test.txt');
foreach ($lines as $line_num => $line) {
echo "Line #{$line_num} : " . htmlspecialchars($line) . "
\n";
}
3.1 fgets — 从文件指针中读取一行
fgets(resource $stream, ?int $length = null): string|false
从文件中读取一行并返回长度最多为 length - 1 字节的字符串。碰到换行符(包括在返回值中)、EOF 或者已经读取了 length - 1 字节后停止(看先碰到那一种情况)。如果没有指定 length,则默认为 1K,或者说 1024 字节。
$fp = fopen("test.txt", "r");
if ($fp) {
while (!feof($fp)) {
$line = fgets($fp);
echo $line . "
\n";
}
fclose($fp);
}
3.2 fread — 从文件指针中读取固定长度(可安全用于二进制文件)
fread(resource $stream, int $length): string|false
$fp = fopen("test.txt", "r");
if ($fp) {
$content = "";
while (!feof($fp)) {
$content .= fread($fp, 1024);
}
#$contents = fread($handle, filesize($filename));
echo $content;
fclose($fp);
}
https://www.php.net/manual/zh/class.splfileobject.php
处理超大文件,比如日志文件时,可以用fseek函数定位,也可以调用linux命令处理
$file = 'access.log';
$file = escapeshellarg($file); // 对命令行参数进行安全转义
$line = `tail -n 1 $file`;
echo $line;
file_put_contents(
string $filename,
mixed $data,
int $flags = 0,
?resource $context = null
): int|false
$content = "Hello, world!"; // 要写入文件的内容
$file = "test.txt"; // 文件路径
file_put_contents($file, $content);
fwrite(resource $stream, string $data, ?int $length = null): int|false
$content = "这是要写入文件的内容";
$file = fopen("test.txt", "w"); // 打开文件写入模式
if ($file) {
fwrite($file, $content); // 将内容写入文件
fclose($file); // 关闭文件
}
copy(string $from, string $to, ?resource $context = null): bool
$file = 'test.txt';
$newFile = 'test2.txt';
if (!copy($file, $newFile)) {
echo "failed to copy $file...\n";
}
unlink(string $filename, ?resource $context = null): bool
$fileName = 'test2.txt';
if (file_exists($fileName)) {
if (unlink($fileName)) {
echo '删除成功';
}
}
rename(string $from, string $to, ?resource $context = null): bool
$fileName = 'test.txt';
$rename = 'test_new.txt';
if (file_exists($fileName)) {
if (rename($fileName, $rename )) {
echo '重命名成功';
}
}