$targetFolder = '/uploads';
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
if (is_uploaded_file($tempFile)) {
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetFile = rtrim($targetPath, '/') . '/' . $_FILES['Filedata']['name'];
$fileTypes = array('jpg','jpeg','gif','png');
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'], $fileTypes)) {
move_uploaded_file($tempFile, $targetFile);
echo '1';
} else { echo '非法文件類型'; }
}
}
IIS 虛擬目錄導致 $_SERVER['DOCUMENT_ROOT'] 指向錯誤路徑,文件上傳成功但無法通過 Web 訪問。
copy() 將臨時文件復制到項目內部目錄rename() 按業務規則重命名$src = $tempDir . '/' . $_POST['temp_filename'];
$dst = $projectDir . '/' . $newName;
if (copy($src, $dst)) {
unlink($src); // 清理臨時文件
// 記錄數據庫...
}
copy() 複製 0 字節文件返回 false 但實際成功,需額外判斷