Question

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?

Was it helpful?

Solution 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);
}

OTHER TIPS

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top