A bit late in the game, but this pair of functions does its job and follows the familiar file name format, followed by "(n)", and then the file extension:
incrementFileName () returns the updated file name increased by 1 with the input file name and destination directory. splitLast () is a diversity modification to split only the last occurrence of some substring.
function incrementFileName($name,$path){
if (!array_search($name,scandir($path))) {
return $name;
} else {
$ext=splitLast($name,".")[1];
$baseFileName=splitLast(splitLast($name,".")[0],"(")[0];
$num=intval(splitLast(splitLast($name,"(")[1],")")[0])+1;
return incrementFileName($baseFileName."(".$num.").".$ext,$path);
}
}
function splitLast($string,$delim) {
$parts = explode($delim, $string);
if (!$parts || count($parts) === 1) {
$before=$string;
$after="";
} else {
$after = array_pop($parts);
$before=implode($delim, $parts);
}
return array($before,$after);
}
When processing the download, specify the file name:
$fileName = incrementFileName($_FILES['file']['name'], $path);
This will return someFileName (1) .jpg or someFileName (2) .jpg, etc.
source
share