0

I try to move a temporary file located in the /tmp dir to another dir somewhere else on the server using the rename() function. But I get an error:

Permission denied (Code: 2)

for the temporary file. How can I move a temporary file to another location? If I check that the file exists with file_exists() I get true. And if I copy() the temporary file it works fine.

Here's my code so far:

 $toPath = '/var/www/htdocs/myproject/some/file.pdf'

 $fileName = 'myfile.pdf';
 $filePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $fileName;

 rename($filePath, $toPath); // Permission denied (Code: 2) here
TiMESPLiNTER
  • 5,741
  • 2
  • 28
  • 64
  • Well, do you have the correct permissions? Don't forget, `copy()` only needs read permissions, to read the file and write it elsewhere. Whereas `rename()` requires permissions to move the file. – Ben Fortune Feb 17 '14 at 13:14
  • Check what is actually returned by sys_get_temp_dir() - as per the docs, it may or may not have a trailing '/' – TonyWilk Feb 17 '14 at 13:15
  • @TonyWilk It does have a trailing slash. The file is also readable. I just wonder why PHP can **create** the file bit than not **rename** it... – TiMESPLiNTER Feb 17 '14 at 13:19
  • So.. is your $filepath ACTUALLY: "temp_dir//$filename" (assuming DIRECTORY_SEPARATOR == '/') ? – TonyWilk Feb 17 '14 at 13:23
  • 1
    The path I get is `/tmp/myfile.pdf` so everything seems to be okay with that. I can eben `unlink()` the temporary file but not use `rename()`. – TiMESPLiNTER Feb 17 '14 at 13:26
  • Ok, as suggested earlier by 'Ben', it must be permissions and/or destination dir/file – TonyWilk Feb 17 '14 at 13:35
  • That's clear. But why can I create, unlink, copy the file but not rename it? – TiMESPLiNTER Feb 17 '14 at 13:42
  • @TiMESPLiNTER I had the same issue, and someone gave a useful tip on another thread: https://stackoverflow.com/questions/25076006/php-move-with-rename-fails-but-combination-of-copy-and-unlink-works#comment39014262_25076006 For me, it was "Invalid cross-device link" because the destination file was on a Windows Share. I ended up copying and then unlinking the file in my PHP code. – Lideln Kyoku Apr 19 '22 at 11:02

1 Answers1

1

this is caused by sticky bit set on the directory:

drwxrwxrwt. 8 root root 4096 Feb 6 09:38 .

sticky bit basically stops non-owners of file to rename or delete the file. It is usually set on /tmp and similar directories where multiple users have write permissions and/or save temporary files in, in order to prevent accidental deletion.

For more info, see: https://www.thegeekstuff.com/2013/02/sticky-bit/