1

I am trying to use PHP's rename to move a file to a different folder (and also rename the file in the same step). However, rename always returns false. On the other hand, using a combination of copy and unlink works just fine. What could be causing this?

The relevant code looks like this:

  if (!rename($targetpath, $backuppath)) {
    // if rename fails, try with copy and delete
    if (!copy($targetpath, $backuppath)) 
      die("9\nCould not move existing file to backup");
    touch($backuppath, filemtime($targetpath));
    if (!unlink($targetpath))
      die("9\nCould not move existing file to backup");
  }

The paths would be e.g.

$targetpath: /path/to/plots/some.pdf
$backuppath: /path/to/plots/old/some.pdfX14068815860
fuenfundachtzig
  • 7,952
  • 13
  • 62
  • 87
  • PHP version is 5.1.6. – fuenfundachtzig Aug 01 '14 at 08:38
  • Is it on Windows ? Seems like `rename` won't work on windows systems if the destination path / file already exists. – Clément Malet Aug 01 '14 at 08:41
  • No, it's Apache/2.2.3 on Scientific Linux. – fuenfundachtzig Aug 01 '14 at 08:43
  • There have been a number of bug fixes for `rename()` in the past: http://php.net/ChangeLog-5.php. Can you reproduce the same problem on a newer PHP version? Is there anything special about your files, e.g. they're symlinks? FWIW: 5.1 on Windows...?! [*shudder*](http://php.net/eol.php) ;) – deceze Aug 01 '14 at 08:58
  • 2
    Most likely a permission error.. please look through the strace for the exact error code rename is giving: `strace php script.php 2>&1 | grep '^rename'` That will give you the exact error code, cross check it with `man 2 rename` to know more. – smassey Aug 01 '14 at 09:03

1 Answers1

0

Start by checking out whet the error was:

print_r(error_get_last());

What version of php are you using? On older versions, rename only works if both source and destination are on the same filesystem. On some systems, rename will also fail if you have an open file descriptor for that file.

jcaron
  • 17,302
  • 6
  • 32
  • 46