Auto increment filename without MySql
August 19th, 2009 — 02:23 pmThere are many cases in witch you have to create an auto incrementing list of files without the use of MySql ( which will easily give you an auto increment field ). In this case you can use the following algorithm to determine the last position you’ve added and create the next one.
First of all there are some rules to follow in the naming of the file:
1. Use the index of the file at the beggining of the name or use the same static prefix
- ex: 0001.jpg, bambi03.jpg
2. Divide the dynamic generated parts of the file name with separation characters
-ex: bambi03_20-10-2008.jpg
3. Use the same number of characters to represent the index number.
-ex: 0001 -> … ->0025 -> … ->9999
The function to determine the last used index works as follows:
-selects the name of the last file in alphabetical order;
-trims out the parts of the file name that are not useful by using string functions;
-return the numerical value of the remaining string;
Here you can see the code that does the job for a list of files representated as “bumbi**.jpg”:
<?php
function getLast()
{
$files=scandir(‘images’,1);
//print $files[0]; //outputs the name of the last fille in alphabetical order (bambi03.jpg)
//get the number of the last fille
$file = $files[0];
$file = str_replace(array(‘bambi’,‘.jpg’),”,$file);
//print $file; //outputs the string containing the last entered number
$nb=(int)$file;
//print $nb; //outputs the numeric value of the last entered number
return $nb;
}
?>