Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP fileupload: keep both files if same name

is there any pretty solution in PHP which allows me to expand filename with an auto-increment number if the filename already exists? I dont want to rename the uploaded files in some unreadable stuff. So i thought it would be nice like this: (all image files are allowed.)

Cover.png
Cover (1).png
Cover (2).png
…
like image 704
YeppThat'sMe Avatar asked Feb 18 '26 08:02

YeppThat'sMe


2 Answers

First, let's separate extension and filename:

$file=pathinfo(<your file>);

For easier file check and appending, save filename into new variable:

$filename=$file['filename'];

Then, let's check if file already exists and save new filename until it doesn't:

$i=1;
while(file_exists($filename.".".$file['extension'])){
 $filename=$file['filename']." ($i)";
 $i++;
}

Here you go, you have a original file with your <append something> that doesn't exist yet.

EDIT: Added auto increment number.

like image 79
Kristjan O. Avatar answered Feb 19 '26 23:02

Kristjan O.


Got it:

if (preg_match('/(^.*?)+(?:\((\d+)\))?(\.(?:\w){0,3}$)/si', $FILE_NAME, $regs)) {
        $filename = $regs[1];
        $copies = (int)$regs[2];
        $fileext = $regs[3];

        $fullfile = $FILE_DIRECTORY.$FILE_NAME;
        while(file_exists($fullfile) && !is_dir($fullfile))
        {
                $copies = $copies+1;
                $FILE_NAME = $filename."(".$copies.")".$fileext;
                $fullfile = $FILE_DIRECTORY.$FILE_NAME;
        }
}
return $FILE_NAME;
like image 26
YeppThat'sMe Avatar answered Feb 19 '26 23:02

YeppThat'sMe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!