while 循环与 operator++ 只计数一次
while loop with operator++ only counting up once
我采用了
的代码
但无法弄清楚为什么在多次上传同一个文件 "test.jpg" 时它只计数一次,创建 "test-1.jpg" 而不是更多,即。测试-2.jpg, 测试-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);
}
你的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
我采用了
的代码但无法弄清楚为什么在多次上传同一个文件 "test.jpg" 时它只计数一次,创建 "test-1.jpg" 而不是更多,即。测试-2.jpg, 测试-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);
}
你的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