文件基礎操作流程
<?php
$file = "test.txt";
// 1. 存在性與類型檢查
if (file_exists($file)) echo "文件存在
";
if (is_file($file)) echo "是文件
";
if (is_dir($file)) echo "是目錄
";
// 2. 權限檢查
if (is_executable($file)) echo "可執行
";
if (is_readable($file)) echo "可讀
";
if (is_writable($file)) echo "可寫
";
chmod($file, 0777); // 修改權限:1=執行 2=寫入 4=讀取,相加組合
// 3. 開啟模式對照
// r 唯讀,指標開頭
// r+ 讀寫,指標開頭
// w 唯寫,截斷/建立,指標開頭
// w+ 讀寫,截斷/建立,指標開頭
// a 追加寫入,指標結尾
// a+ 追加讀寫,指標結尾
// b 二進制模式 (Windows 必須)
$fp = fopen($file, "a+"); // 追加讀寫開啟
?>
讀取操作
<?php
// 讀取指定字節
$content = fread($fp, 70);
echo "1. {$content}
";
// 寫入 (追加模式)
fwrite($fp, "我是薦禮啦...");
// 讀取全部內容 (推薦)
$content = file_get_contents($file);
echo "2. {$content}
";
// 寫入全部 (覆蓋)
file_put_contents($file, "新內容...");
fclose($fp); // 關閉句柄
// 重新開啟讀取全部
$fp = fopen($file, "a+");
$content = fread($fp, filesize($file));
echo "3. {$content}
";
// 逐字符/逐行讀取
$fp = fopen($file, "r");
echo "單字符: " . fgetc($fp) . "
";
$fp = fopen($file, "r");
echo "單行: " . fgets($fp) . "
";
// 輸出剩餘所有 (適合二進制文件下載)
$fp = fopen($file, "r");
fpassthru($fp);
?>
文件系統操作
<?php
copy("test.txt", "薦禮啦.txt"); // 複製
if (file_exists("愛我爸媽.txt")) unlink("愛我爸媽.txt"); // 刪除文件
rename("薦禮啦.txt", "愛我爸媽.txt"); // 重命名/移動
// 目錄操作
if (file_exists("薦禮啦")) rmdir("薦禮啦"); // 刪除空目錄
else mkdir("薦禮啦", 0777, true); // 遞歸建立目錄
?>
文件資訊獲取
<?php
$file = "test.txt";
echo "大小: " . filesize($file) . " 字節
";
echo "類型: " . filetype($file) . "
"; // file/dir/link/fifo/block/char/unknown
$fp = fopen($file, "r");
print_r(fstat($fp)); // 關聯陣列:dev, ino, mode, nlink, uid, gid, rdev, size, atime, mtime, ctime, blksize, blocks
fclose($fp);
print_r(stat($file)); // 同 fstat,參數為路徑
echo "當前文件: " . __FILE__ . "
";
echo "所在目錄: " . dirname(__FILE__) . "
";
echo "文件名: " . basename(__FILE__) . "
";
?>
實用封裝建議
<?php
class FileUtil {
public static function read($path) { return @file_get_contents($path); }
public static function write($path, $data, $append = false) {
return @file_put_contents($path, $data, $append ? FILE_APPEND : 0);
}
public static function jsonRead($path) { return json_decode(self::read($path), true); }
public static function jsonWrite($path, $data) { return self::write($path, json_encode($data, JSON_UNESCAPED_UNICODE)); }
public static function ensureDir($dir) { if (!is_dir($dir)) mkdir($dir, 0755, true); }
public static function listFiles($dir, $pattern = '*') {
return glob(rtrim($dir, '/') . '/' . $pattern);
}
}
?>