PHP 文件操作
PHP 提供了完整的文件系统操作函数,可以读写文件、管理目录。
读取文件
// 一次性读取整个文件 $content = file_get_contents('data.txt'); echo $content;`// 读取为数组(每行一个元素) $lines = file('data.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); foreach ($lines as $line) { echo $line . "\n"; }
// 逐行读取大文件(节省内存) $handle = fopen('large.txt', 'r'); while (!feof($handle)) { $line = fgets($handle); echo $line; } fclose($handle); ?> ``
写入文件
php <?php // 覆盖写入 file_put_contents('output.txt', "Hello, World!\n");`// 追加写入 file_put_contents('log.txt', date('Y-m-d H:i:s') . " 操作日志\n", FILE_APPEND);
// 使用 fopen 写入 $handle = fopen('data.txt', 'w'); // w=覆盖, a=追加, r=只读 fwrite($handle, "第一行\n"); fwrite($handle, "第二行\n"); fclose($handle); ?>
`文件模式说明
模式 说明 r 只读,指针在开头 w 只写,清空文件或创建新文件 a 追加,指针在末尾 r+ 读写,指针在开头 w+ 读写,清空文件 x 创建并写入,文件已存在则失败 文件信息
php <?php $file = 'example.txt';`echo file_exists($file) ? "存在" : "不存在"; echo is_file($file) ? "是文件" : ""; echo is_readable($file) ? "可读" : ""; echo is_writable($file) ? "可写" : "";
echo filesize($file); // 文件大小(字节) echo date('Y-m-d', filemtime($file)); // 最后修改时间 echo pathinfo($file, PATHINFO_EXTENSION); // 扩展名 echo basename($file); // 文件名 echo dirname($file); // 目录路径 echo realpath($file); // 绝对路径 ?>
`文件与目录管理
php <?php // 复制、移动、删除 copy('source.txt', 'dest.txt'); rename('old.txt', 'new.txt'); // 也可用于移动文件 unlink('delete.txt'); // 删除文件`// 目录操作 mkdir('new_dir', 0755, true); // 递归创建目录 rmdir('empty_dir'); // 删除空目录 $files = scandir('.'); // 列出目录内容
// 递归列出所有文件 $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator('./articles') ); foreach ($iterator as $file) { if ($file->isFile()) { echo $file->getPathname() . "\n"; } } ?>
`CSV 文件处理
php <?php // 写入 CSV $data = [ ["姓名", "年龄", "城市"], ["张三", 25, "北京"], ["李四", 30, "上海"], ];`$handle = fopen('users.csv', 'w'); foreach ($data as $row) { fputcsv($handle, $row); } fclose($handle);
// 读取 CSV $handle = fopen('users.csv', 'r'); while (($row = fgetcsv($handle)) !== false) { echo implode(', ', $row) . "\n"; } fclose($handle); ?>
`JSON 文件处理
php <?php // 写入 JSON $config = [ 'debug' => false, 'version' => '1.0.0', 'database' => ['host' => 'localhost', 'port' => 3306], ]; file_put_contents('config.json', json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));`// 读取 JSON $json = file_get_contents('config.json'); $config = json_decode($json, true); // true 返回数组,false 返回对象 echo $config['version']; // 1.0.0 ?>
``php <?php $handle = fopen('counter.txt', 'c+');文件锁(并发安全)
if (flock($handle, LOCK_EX)) { // 独占锁 $count = (int)fread($handle, 100); $count++; rewind($handle); fwrite($handle, $count); ftruncate($handle, ftell($handle)); flock($handle, LOCK_UN); // 释放锁 }
fclose($handle);