我采用了来自https://stackoverflow.com/a/44553006/8719001
的代码但无法确定上传相同文件的原因" test.jpg"好几次它只算一次,创造了" test-1.jpg"但不是更多,即。 test-2.jpg,test-3.jpg。
有人可以发现问题,请帮忙吗?
$keepFilesSeperator = "-";
$keepFilesNumberStart = 1;
if (isset($_FILES['upload'])) {
// Be careful about all the data that it's sent!!!
// Check that the user is authenticated, that the file isn't too big,
// that it matches the kind of allowed resources...
$name = $_FILES['upload']['name'];
//If overwriteFiles is true, files will be overwritten automatically.
if(!$overwriteFiles)
{
$ext = ".".pathinfo($name, PATHINFO_EXTENSION);
// Check if file exists, if it does loop through numbers until it doesn't.
// reassign name at the end, if it does exist.
if(file_exists($basePath.$name))
{
$operator = $keepFilesNumberStart;
//loop until file does not exist, every loop changes the operator to a different value.
while(file_exists($basePath.$name.$keepFilesSeperator.$operator))
{
$operator++;
}
$name = rtrim($name, $ext).$keepFilesSeperator.$operator.$ext;
}
}
move_uploaded_file($_FILES["upload"]["tmp_name"], $basePath . $name);
}
答案 0 :(得分:1)
你的while循环条件有问题
while( file_exists( $basePath.$name.$keepFilesSeperator.$operator ) )
$ name 变量仍然包含文件的全名,在本例中为 test.jpg ,您正在测试类似 / home / test的值.jpg-1 所以最后while循环永远不会执行,因为文件 test.jpg-1 从不存在,这就是为什么你总是得到 test-1.jpg 强>在磁盘而不是 ...- 2.jpg 或 ...- 3.jpg