I tried the below incrementer and it works on first go, but then it doesn't.

For example:

1) Upload file: "picture.png" -----> stores picture.png | OK

2) Upload File: "picture.png" -----> changes picture.png to 1picture.png | OK

3) Upload File: "picture.png" -----> Doesn't work, directory only have the 2 pictures above.

if(file_exists($path . $picName)) {
   $incrementer = 1;
   $path =  $path . $incrementer++;  
   move_uploaded_file($tmp, $path . $picName);
}

How come it doesn't increment no more?

有帮助吗?

解决方案 2

You keep resetting your $incrementer on each loop iteration. You need to set it outside of your loop:

$incrementer = 1;
// start loop
  if(file_exists($path . $picName)) {
     $path =  $path . $incrementer++;  
     move_uploaded_file($tmp, $path . $picName);
  }
// end loop

If the files are being uploaded one at a time then this won't work at all as your PHP script, including all of the variables you set in it end with each execution of that script. In that case you would need to save that value in a database, session, or some other (semi-)persistent storage so it would be available across script executions.

session_start();
if (!isset($_SESSION[incrementer']) 
    $_SESSION[incrementer'] = 1;
}
if(file_exists($path . $picName)) {
    $path =  $path . $_SESSION['incrementer']++;  
    move_uploaded_file($tmp, $path . $picName);
}

其他提示

You need to check if file already exist already then change the file-name. To make filne-name unique I mostly append CurrentTime before the file-name. You can use the Random-Number also.

$picName = time().$picName;
while(file_exists($path . $picName))
{
   $picName = time().$picName;
}

move_uploaded_file($tmp, $path . $picName);

you need a while loop:

$incrementer = 1;
$basepath='path/';
$path =  $basepath; 

while(file_exists($path . $picName)) {
   $path =  $basepath . ($incrementer++);  
}

move_uploaded_file($tmp, $path . $picName);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top