[英]while loop with operator++ only counting up once
I adopted code from https://stackoverflow.com/a/44553006/8719001 我通过了https://stackoverflow.com/a/44553006/8719001的代码
but can't figure out why when uploading the same file "test.jpg" several times it only counts up once, creating "test-1.jpg" but not more ie. 但无法弄清楚为什么多次上传同一文件“ test.jpg”时,它只计数一次,创建“ test-1.jpg”却没有,例如。 test-2.jpg, test-3.jpg. test-2.jpg,test-3.jpg。
Can anybody spot the issue and help please? 有人可以发现问题并提供帮助吗?
$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);
}
your while loop condition has a problem 您的while循环条件有问题
while( file_exists( $basePath.$name.$keepFilesSeperator.$operator ) )
the $name variable still contains the full name of file, in this case test.jpg , you're testing a value like /home/test.jpg-1 so finally the while loop is never executed as the file test.jpg-1 never exists, that's why you always get the test-1.jpg on disk and not a ...-2.jpg or ...-3.jpg $ name变量仍然包含文件的全名,在本例中为test.jpg ,您正在测试/home/test.jpg-1之类的值,因此最终while循环永远不会作为文件test.jpg-1执行。永远不会存在,这就是为什么您总是在磁盘上获得test-1.jpg而不是...- 2.jpg或...- 3.jpg的原因
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.