<?php
// 一行搞定:第三參數 true 啟用遞迴建立
mkdir('/path/to/deep/nested/dir', 0755, true);
// 完整錯誤處理版
function make_directory($path, $mode = 0755) {
// 統一路徑分隔符
$path = str_replace('\\', '/', $path);
if (is_dir($path)) return true; // 已存在
// 遞迴建立,抑制警告自行處理錯誤
if (@mkdir($path, $mode, true)) {
return true;
}
// 失敗時檢查具體原因
$error = error_get_last();
throw new RuntimeException("無法建立目錄 '$path': " . $error['message']);
}
原文提供的手動分層建立邏輯:
function makedirectory($directoryname) {
$directoryname = str_replace('\\', '/', $directoryname);
$dirnames = explode('/', $directoryname);
$total = count($dirnames);
$temp = '';
for ($i = 0; $i < $total; $i++) {
$temp .= $dirnames[$i] . '/';
if (!is_dir($temp)) {
$oldmask = umask(0); // 暫時移除 umask 限制
if (!mkdir($temp, 0777)) { // 建立單層
umask($oldmask);
exit("不能建立目錄 $temp");
}
umask($oldmask); // 還原 umask
}
}
return true;
}
umask(0):暫時關閉權限遮罩,確保 `mkdir($path, 0777)` 真正給 0777 權限function ensure_dir($path, $mode = 0755) {
// 1. 正規化路徑
$path = rtrim(str_replace('\\', '/', $path), '/');
// 2. 已存在直接返回
if (is_dir($path)) return true;
// 3. 父目錄不存在時遞迴建立(PHP 原生遞迴)
$parent = dirname($path);
if (!is_dir($parent)) {
ensure_dir($parent, $mode);
}
// 4. 建立當前層,處理競態條件(並發建立同目錄)
@mkdir($path, $mode);
if (!is_dir($path)) {
// 可能被其他程序同時建立完成,或權限不足
throw new RuntimeException("建立目錄失敗: $path");
}
// 5. 確保權限正確(某些檔案系統需額外 chmod)
@chmod($path, $mode);
return true;
}
function get_upload_dir($base = '/var/www/uploads') {
$date = date('Y/m/d');
$dir = "$base/$date";
ensure_dir($dir);
return $dir;
}
// 使用
$upload_dir = get_upload_dir();
$target = $upload_dir . '/' . uniqid() . '_' . basename($_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], $target);
function get_cache_path($key) {
// 以 key 前兩字元分層,避免單目錄檔案過多
$prefix = substr(md5($key), 0, 2);
$dir = "/tmp/cache/$prefix";
ensure_dir($dir);
return "$dir/$key.cache";
}
| 場景 | 建議模式 | 說明 |
|---|---|---|
| Web 可寫入目錄 | 0755 | 擁有者寫入,群組/其他讀取執行 |
| 上傳/快取目錄 | 0775 | 群組也可寫入(需設定正確群組) |
| 私密資料目錄 | 0700 | 僅擁有者可存取 |