0

I am trying to copy a file to another directory, but to prevent overwriting a file inside it with the same name, I check it first and if a file with the same name already exists, then I want to rename the file from, lets say file.jpg to file(1).jpg and copy it. I do not succeed in renaming it "on the fly".

This is what I have so far:

$src_file_url = $_POST['copyfile']; //eg uploads/name/file.jpg
$fileName = basename($src_file_url);

$new_dest = $_POST['copyfile-destination'];

/* New file name and path for this file */
$dest_file = 'uploads/'.$UserID.'/'.$new_dest.'/'.$fileName;

if (file_exists($dest_file)) {
rename($src_file_url, $fileName.'(1)');
copy( $src_file_url, $dest_file );
exit;
}
Abdul Hoque Nuri
  • 1,105
  • 1
  • 9
  • 18
Jack Maessen
  • 1,780
  • 4
  • 19
  • 51
  • You should rename `$dest_file` not `$src_file_url`, right? What does `do not succeed` mean, you get an error, it renames the wrong file, it doesn't rename anything, other? – user3783243 Jan 08 '19 at 13:58
  • what happens: it renames my source file. and the name of the source file should stay exactly the same – Jack Maessen Jan 08 '19 at 14:00
  • 1
    You tell it to rename the source file here `rename($src_file_url`. If you don't want it to use the same name just change the value in the `copy` function, the second parameter. That is the value it will be written as. Maybe `$dest_file = 'uploads/'.$UserID.'/'.$new_dest.'/'. (file_exists($dest_file) ? '(1)' : '' ) . $fileName;` then you just need the `copy( $src_file_url, $dest_file );`... or rather move the ternary outside since `$dest_file` is undefined at that point – user3783243 Jan 08 '19 at 14:18

0 Answers0