在PHP中,當你上傳文件時,可能會遇到文件名沖突的問題。為了解決這個問題,你可以采取以下幾種方法:
uniqid()
函數生成一個唯一的字符串,并將其添加到文件名中。例如:$unique_filename = uniqid() . '_' . $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $unique_filename);
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
if (file_exists($target_file)) {
// 選擇覆蓋原文件
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
} else {
// 或者重命名新文件
$new_filename = uniqid() . '_' . basename($_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir . $new_filename);
}
file_1.txt
、file_2.txt
等),直到找到一個不存在的文件名。例如:$target_dir = "uploads/";
$original_filename = basename($_FILES["file"]["name"]);
$extension = pathinfo($original_filename, PATHINFO_EXTENSION);
$filename_without_extension = pathinfo($original_filename, PATHINFO_FILENAME);
$counter = 1;
$new_filename = $original_filename;
while (file_exists($target_dir . $new_filename)) {
$new_filename = $filename_without_extension . "_" . $counter . "." . $extension;
$counter++;
}
move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir . $new_filename);
這樣,你就可以在上傳文件時處理文件名沖突,確保文件被正確保存。