How to move/copy a file and rename if conflict

508 views Asked by At

Is there some API/Library to move or copy a file and then have an option to rename the new file if there is a conflict with another file existing in the destination?

I am using Wakanda and there is a File API which has a moveTo method. This method has an parameter which is overwrite, if we pass true or 'Overwrite' and false or 'KeepExisting'. This method forget one option, which is a classic when dealing with file, is : 'KeepBoth'. That mean it gonna rename the new file with a counter.

For now, I add an UUID at the end of the file.

I'm wondering how other API handle this case when we need to move and rename in case of conflict.

1

There are 1 answers

2
oshell On

Normally you will use ajax and call a server side script to check if the file exists. You could add a number to the file name to prevent a conflict.

PHP example

$path = "link/to/path";
$chk = $path;
$i = 0;

while (file_exists($chk)){
    $chk = $path.$i
    $i++;
}

If you want to overwrite it you would simply use

file_put_contents($path, $content);