I think this is your best bet (see revisions for previous versions):
$files = glob('/path/to/dir/*'); // get all files in folder
natsort($files); // sort
$lastFile = pathinfo(array_pop($files)); // split $lastFile into parts
$newFile = $lastFile['filename'] +1; // increase filename by 1
if(file_exists("/path/to/dir/$newFile")) { // do not write file if it exists
die("$newFile aready exists");
}
file_put_contents("/path/to/dir/$newFile", 'stuff'); // write new file
As long as your filenames in the folder start with numbers, this should always write the highest numbered filename incremented by one, e.g.
1,5,10 => writes file 11
1.txt, 5.gif, 10.jpg => writes file 11
1, 5.txt, 10_apple.txt => writes file 11
If there is a file not starting with a number, the above approach won't work, because numbers are sorted before characters and thus nothing would be written for e.g.
1,5,10,foo => foo+1 equals 1, already exists, nothing written
You can get around this by changing the pattern for glob to /path/[0-9]*, which would then only match files starting with a number. That should be pretty solid then.
Note natsort behaves different on different OS. The above works fine on my Windows machine, but you will want to check the resulting sort order to get it working for your specific machine.
See the manual for further info on how to use glob(), natsort() and pathinfo();