Rename upload file (sorting)

Hi

I have directory and it’s files like this(

1.doc
2.doc
3.doc
)

I want when upload new file to this directory change name to be (lastno+1.doc)
if last doc like example(3.doc) when upload new one rename to be(4.doc)

any help??

Hi altarek,

Try this:


$count = 1;
while (file_exists($targetDir . DIRECTORY_SEPARATOR . $count . '.doc'))
    $count++;

$fileName = $count . '.doc';

It basically loops checking if a file exists called 1.doc, 2.doc etc to find the next available filename.

but if i have one file (20.doc) by this way the new file name will be(1.doc)

I want it to be (21.doc)

??

This may be of help…
http://www.epigroove.com/blog/use-php-to-count-number-of-files-in-a-directory

OK, in that case try this:


$last_used_number = 0;
$files = scandir('folder/');

foreach($files as $file) {
  $info = pathinfo($file);
  if (is_numeric($info['filename']) AND $info['filename'] > $last_used_number) {
    $last_used_number = $info['filename'];
  }
}

$file_name = ($last_used_number + 1) . '.doc';

Or simplier:


$next = count( glob( 'directory/to/files/*.doc' ) ) + 1;
print $next . '.doc';

Edilt, looks like the above link is that samething…oh well. Didn’t read the link until now.

logic_earth, that’s a nice solution to counting the number of files in a directory. The problem is if you had just one file named 20.doc, this method would give you 2.doc rather than 21.doc as altarek says he wants.

Adapt as necessary…


<?php
$files = glob('*.doc');
$c= count($files);
$i = 0;
while($i<$c) {
	$temp_array  = explode(".", $files[$i]);
	$temp_values[$i] = $temp_array[0];
	$i ++;
}
sort($temp_values);
$last = $c - 1;
$next = $temp_values[$last] + 1;
$file_name = $next . ".doc";
echo $file_name;
?>


How would that code I posted give you 2 instead of 21? That makes no logical sense. We are pulling in all files that match the pattern and counting them. If their is 20 files we will get 21 within “$next” as it should be.

Please, elaborate how you got 2 when adding one to 20.

You need to examine my code more closely. You should see I am using “count() + 1” directly. If there are 20 files, count() will be 20, what happens then? We will get 21 from the plus one.

Your method counts the number of files in the directory, rather than finding the next unused number in the sequence… I’m not sure when you would need it to work like this, but altarek presumably knows what he wants. Perhaps files 1.doc to 19.doc get periodically moved to a different location, who knows?