首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 檔案與目錄操作完整指南:讀、寫、刪、屬性一覽

     編輯:PHP 綜合知識

一、目錄操作

基本目錄掃描

使用 opendir()、readdir()、closedir() 組合:

<?php
$base_dir = "filelist/";
$handle = opendir($base_dir);
echo $base_dir . "<hr>";
while (false !== ($entry = readdir($handle))) {
    echo $entry . "<br>";
}
closedir($handle);
?>

實用路徑函數

  • dirname($path):取得目錄部分
  • basename($path):取得檔名部分
  • disk_free_space($path):取得磁碟剩餘空間

建立與刪除目錄

<?php
mkdir($path, 0777); // 權限 0777,非 Windows 可用 umask() 設定
rmdir($path);       // 刪除空目錄
?>

Directory 類別(物件導向風格)

<?php
$d = dir("/etc/php5");
echo "Handle: " . $d->handle . "\n";
echo "Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
    echo $entry . "\n";
}
$d->close();
?>

二、檔案操作

檢查檔案可讀性與存在性

<?php
$file = 'dirlist.php';
if (!is_readable($file)) {
    die('檔案不存在或無法讀取');
}
// 或使用 file_exists()
if (!file_exists($file)) {
    die('檔案不存在');
}
?>

is_readable() 同時檢查存在與權限,比 file_exists() 更完整。

讀取檔案內容

推薦(PHP 4.3+): file_get_contents()

<?php
$data = file_get_contents($file);
echo htmlentities($data);
?>

舊版相容寫法:

<?php
$fp = fopen($file, 'r');
$data = fread($fp, filesize($file));
fclose($fp);
// 或讀取二進位檔
$data = implode('', file($file));
?>

寫入檔案

先確認可寫:

<?php
if (!is_writable($file)) {
    die('無法寫入');
}
?>

推薦(PHP 5+): file_put_contents()

<?php
$data = '要寫入的內容';
file_put_contents($file, $data);
?>

舊版/需鎖定時:

<?php
$fp = fopen($file, 'w');
flock($fp, LOCK_EX); // 獨佔鎖定
fwrite($fp, $data);
flock($fp, LOCK_UN); // 釋放鎖定
fclose($fp);
?>

複製、刪除、重命名

<?php
// 刪除
unlink($file);

// 複製
copy($source, $dest);

// 重命名/移動
rename($old, $new);
?>

取得檔案屬性

功能函數說明
最後修改時間filemtime()回傳 Unix 時間戳,常用於快取驗證
最後存取時間fileatime()
inode 變更時間filectime()權限、擁有者變更時更新
檔案擁有者fileowner()搭配 posix_getpwuid() 取得用戶名(非 Windows)
檔案權限fileperms()配合 sprintf('%o', ...) 取得八進位表示
檔案大小filesize()位元組數
完整屬性陣列stat()回傳關聯陣列,含所有上述資訊

三、常見陷阱與提醒

  • Windows 不區分大小寫,Linux 區分,部署時注意路徑大小寫。
  • 目錄權限需設為可寫(0777 或 0755),否則建立檔案會失敗。
  • 大檔案讀寫建議使用串流(stream)避免記憶體耗盡。
  • file_get_contents() 若開啟 allow_url_fopen 可直接讀取遠端 URL,但需設定逾時避免阻塞。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved