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
Strange this one doesn’t work on my site.
My goal is to restrict users to upload only 10 pics each (from 1 to 10) … picture_1-10.jpg.
If a user decided to delete a picture, for example picture_7.jpg and upload a new one the picture should be renamed with the same title as the deleted one.
Any suggestions? Thanks in advance.
Here is my PHP script:
If the filename has no extension, then php will complain that $$ext variable is not set.
You should change this code:
with this:
How to download my file from already uploaded path?. What function i will used.? please help me
Thanks for sharing. useful to me.
Thanks to share the Logic, it is very useful……
This will not work well if you upload an already renamed file.
E.g. : if you upload “myfile_1.jpg” it will rename it to “myfile_1_1.jpg”.
You have to check for “_NUMBER” in the file and increment that number.