# 遞歸賦予讀寫執行權限(開發環境可用,生產請最小權限原則) chmod -R 777 /var/www/html/uploads # 或針對特定目錄 chmod a+rwx /var/www/html/uploads
確保 Web 伺服器使用者(www-data、apache、nginx)具寫入權限。
$siteRoot = dirname(__FILE__); // PHP 5.3+ 推薦 __DIR__ $uploadDir = $siteRoot . '/uploads/';
post_max_size = 200M upload_max_filesize = 200M max_execution_time = 300 max_input_time = 300
修改後需重啟 PHP-FPM/Apache 生效。
$aimUrl = str_replace('\\', '/', $aimUrl); // 統一分隔符
$aimDir = '';
$parts = explode('/', $aimUrl);
foreach ($parts as $part) {
$aimDir .= $part . '/';
if (!file_exists($aimDir)) {
mkdir($aimDir, 0777, true); // true 遞歸建立
chmod($aimDir, 0777);
}
}
適用於 uploads/2024/01/15/ 等結構。
finfo_file() 或 mime_content_type()in_array($ext, ['jpg','png','pdf'])md5(time().rand()).'.'.$ext 避免覆蓋與執行location ~ \.php$ { deny all; }、Apache SetHandler default-handlerif ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
$tmp = $_FILES['file']['tmp_name'];
$ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
if (!in_array($ext, ['jpg','png','gif','pdf'])) {
die('副檔名不允許');
}
$newName = md5_file($tmp) . '.' . $ext;
$dateDir = date('Y/m/d/');
$targetDir = $uploadDir . $dateDir;
if (!is_dir($targetDir)) mkdir($targetDir, 0755, true);
$target = $targetDir . $newName;
if (move_uploaded_file($tmp, $target)) {
echo "上傳成功:$target";
} else {
echo "移動失敗";
}
}