我正在创建文件上传器,并检查文件是否存在于目录中。如果确实存在,我必须为该文件提出一个新名称(I.E file.txt - > file1.txt)。不知道为什么,但它一直在产生错误。这是我的代码。希望它不是一件非常明显的事情。
$directory = "files/";
$name = $_FILES['filename']['name'];
$valid_name = true;
$counter = 0;
if(file_exists($directory . $_FILES['filename']['name'])) {
$valid_name = false;
}
while(!$valid_name){
$name = $_FILES['filename']['name'] . $counter;
if(file_exists($directory . $name)){
counter++;
}
}
答案 0 :(得分:1)
你的代码错了。这更简单,更容易理解。
$directory = "files/";
$counter = 0;
$name = $_FILES['filename']['name'];
while(file_exists($directory . $name)){
$counter++;
$name = $_FILES['filename']['name'] . $counter;
}
此外,您的代码不会生成file.txt -> file1.txt
,但file.txt -> file.txt1
也会生成此代码。要正确生成它,请使用扩展名和名称。
答案 1 :(得分:1)
使用它时忘了正确命名变量:
$counter++;
// not counter++ but $counter++;
答案 2 :(得分:1)
您忘记更改$valid_name
的值。无论如何,更简单的方法就是:
$directory = "files/";
$counter = "";
while (file_exists($directory . $_FILES['filename']['name'] . $counter)) {
$counter++;
}
// Here the name is: $directory . $_FILES['filename']['name'] . $counter
考虑到第一次执行$counter++
后,它变为“1”,然后是2,等等......
较小的代码,只是为了好玩:
$c = "";
while (file_exists("files/".$_FILES['filename']['name'].$c)) $c++;
// Here the name is: "files/".$_FILES['filename']['name'].$c
答案 3 :(得分:0)
代码有很多问题,我将列出后面的清理。
尝试这样的事情:
$directory = "files/";
$path = pathinfo( $directory . $_FILES['filename']['name'] );
$name = $path['filename'];
$counter = 0;
while ( file_exists( $path['dirname'] . $path['basename'] ) ) {
$counter++;
$path['filename'] = $name . $counter;
}
$outputFile = $path['dirname'] . $path['filename'] . '.' . $path['extension'];