Revision: 46340
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at May 17, 2011 19:56 by dubogii
Initial Code
If the file name exists, returns new file name with _number appended so you don't overwrite it.
function file_newname($path, $filename){
if ($pos = strrpos($filename, '.')) {
$name = substr($filename, 0, $pos);
$ext = substr($filename, $pos);
} else {
$name = $filename;
}
$newpath = $path.'/'.$filename;
$newname = $filename;
$counter = 0;
while (file_exists($newpath)) {
$newname = $name .'_'. $counter . $ext;
$newpath = $path.'/'.$newname;
$counter++;
}
return $newname;
}
Example returns:
myfile.jpg
myfile_0.jpg
myfile_1.jpg
Initial URL
http://css-tricks.com/snippets/php/check-if-file-exists-append-number-to-name/
Initial Description
Initial Title
Check if File Exists / Append Number to Name
Initial Tags
number
Initial Language
PHP