使用 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); // 刪除空目錄
?>
<?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() | 回傳關聯陣列,含所有上述資訊 |
file_get_contents() 若開啟 allow_url_fopen 可直接讀取遠端 URL,但需設定逾時避免阻塞。