php实现文件读写操作
PHP 文件读取操作
使用 file_get_contents() 函数可以快速读取文件内容。该函数将整个文件读入一个字符串中,适合处理较小的文件。
$fileContent = file_get_contents('example.txt');
echo $fileContent;
逐行读取文件可以使用 fopen() 和 fgets() 组合。这种方式适合处理大文件,避免内存问题。
$handle = fopen('example.txt', 'r');
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo $line;
}
fclose($handle);
}
PHP 文件写入操作
使用 file_put_contents() 函数可以简单地将内容写入文件。如果文件不存在会自动创建,默认会覆盖原有内容。
$data = "Hello, World!";
file_put_contents('example.txt', $data);
追加内容到文件末尾需要设置 FILE_APPEND 标志。

$data = "New line of text";
file_put_contents('example.txt', $data, FILE_APPEND);
使用 fopen() 和 fwrite() 进行更灵活的文件写入操作。
$handle = fopen('example.txt', 'w');
if ($handle) {
fwrite($handle, "Some text to write");
fclose($handle);
}
检查文件是否存在
在操作文件前应该检查文件是否存在,避免错误。

if (file_exists('example.txt')) {
echo "File exists";
} else {
echo "File does not exist";
}
文件权限处理
确保脚本有足够的权限读写文件,可以使用 is_readable() 和 is_writable() 检查权限。
if (is_writable('example.txt')) {
echo "File is writable";
} else {
echo "File is not writable";
}
错误处理
文件操作应该包含错误处理机制,使用 try-catch 块捕获可能的异常。
try {
$content = file_get_contents('nonexistent.txt');
echo $content;
} catch (Exception $e) {
echo "Error reading file: " . $e->getMessage();
}
文件锁定机制
在多进程/线程环境下操作文件时,应该使用文件锁定避免冲突。
$fp = fopen('example.txt', 'w');
if (flock($fp, LOCK_EX)) {
fwrite($fp, "Data to write");
flock($fp, LOCK_UN);
} else {
echo "Couldn't get the lock!";
}
fclose($fp);






