I am working on an upload script. It is basically a modified one I found online, and I am wondering how to make it add a number to the back of the file name (such as if file.
php is in the folder, it will name another upload of it file1.
php and so on) if one under that name already exists instead of it just kicking back. It uses the below code to see if it exists already..
- PHP: Select all
if(file_exists($upload_dir.$file_name)){
echo "The file <b>$file_name</b> already exists. <br><a href=\"$_SERVER[PHP_SELF]\">back</a>";
exit();
}
I have a
CGI script that does this to possibly aid anyone who helps me.
- Code: Select all
foreach(@existing_files){
if($_ eq $filename){
$exists = 1;
}
}
# if it exists, we need to rename the file being uploaded and then recheck it to
# make sure the new name does not exist
if($exists){
$newnum++; # increment new number (add 1)
# get the extension
@file_type = split(/\./, $filename); # split the dots and add inbetweens to a list
# put the first element in the $barename var
$bareName = $file_type[0];
# we can assume everything after the last . found is the extension
$file_type = $file_type[$#file_type];
# $#file_type is the last element (note the pound or hash is used)
# remove all numbers from the end of the $bareName
$bareName =~ s/\d+$//ig;
# concatenate a new name using the barename + newnum + extension
$filename = $bareName . $newnum . '.' . $file_type;
# reset $exists to 0 because the new file name is now being checked
$exists = 0;