【发布时间】:2018-03-20 19:21:51
【问题描述】:
我采用了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);
}
【问题讨论】:
-
你不将每个文件的变量 $operator 重新定义为 1 吗?我的意思是,你可以只上传 1 个文件还是 2 个文件(test-1.jpg 和 test-2.jpg)?
-
file_exists($basePath.$name.$keepFilesSeperator.$operator)应该是file_exists($basePath.rtrim($name, $ext).$keepFilesSeperator.$operator.$ext),因为这是您将它们移动到的地方。 -
@I-V 运算符从 1 开始,并在 while 循环中以 ++ 向上计数。逻辑检查适用于每个单独的上传。
-
@JonStirling 感谢您发布实际代码,这很有效!我怀疑它没有被触发但不知道为什么,因为我在循环之后有 rtrim 但意识到它仍然需要它来实际写出新文件名:)。
标签: php while-loop operator-keyword character-trimming