<?php
$base_dir = "filelist/";
$fso = opendir($base_dir);
echo $base_dir . "<hr/>";
while ($flist = readdir($fso)) {
echo $flist . "<br/>";
}
closedir($fso);
?>
返回目錄下所有文件與子目錄名稱,失敗返回 false。
dirname($path):取得目錄部分。basename($path):取得文件名部分。disk_free_space($path):查看磁碟剩餘空間。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('文件不存在或無法讀取');
echo '存在';
?>
一次性讀取全文(PHP 5+ 推薦):
<?php
$file = "filelist.php";
if (!file_exists($file)) die('文件不存在');
$data = file_get_contents($file);
echo htmlentities($data);
?>
低版本兼容寫法:
$fso = fopen($cacheFile, 'r');
$data = fread($fso, filesize($cacheFile));
fclose($fso);
二進制安全讀取:
$data = implode('', file($file));
檢查可寫性:
<?php
$file = 'dirlist.php';
if (!is_writable($file)) die("無法寫入");
?>
PHP 5+ 簡潔寫法:
<?php
$file = 'dirlist.php';
if (!is_writable($file)) die('無法寫入');
$data = '寫入內容';
file_put_contents($file, $data);
?>
低版本兼容寫法:
$f = fopen($file, 'w');
fwrite($f, $data);
fclose($f);
獨佔鎖寫入(防併發衝突):
function cache_page($pageurl, $pagedata) {
if (!$fso = fopen($pageurl, 'w')) return false;
if (!flock($fso, LOCK_EX)) { fclose($fso); return false; }
if (!fwrite($fso, $pagedata)) { flock($fso, LOCK_UN); fclose($fso); return false; }
flock($fso, LOCK_UN);
fclose($fso);
return true;
}
// 刪除
$result = @unlink($file);
// 複製(目標目錄必須可寫)
$result = copy($file, $newfile);
// 重命名/移動
rename($oldPath, $newPath);
常用函數:filemtime()(修改時間)、filesize()、fileowner()、filegroup()、filetype()、fileperms() 等。
熟練掌握上述函數組合,可高效實現 CMS 系統中目錄掃描、靜態文件生成、緩存讀寫、上傳管理等核心功能。實際項目中務必加入錯誤判斷與權限檢查,確保健壯性。