rename

(PHP 4, PHP 5, PHP 7)

rename重命名一个文件或目录

说明

rename ( string $oldname , string $newname [, resource $context ] ) : bool

尝试把 oldname 重命名为 newname

参数

oldname

Note:

用于 oldname 中的封装协议必须和用于 newname 中的相匹配。

newname

新的名字。

context

Note: 在 PHP 5.0.0 中增加了对上下文(Context)的支持。有关上下文(Context)的说明参见 Streams

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

更新日志

版本 说明
5.3.1 可以在 Windows 上跨驱动器 rename() 文件。
5.0.0 rename() 也可用于某些 URL 封装协议。参见支持的协议和封装协议 的列表看看 rename() 支持哪些 URL 封装协议。
4.3.3 在有适当权限的时候 rename() 已经能够在基于 *nix 的系统中跨磁盘分区重命名文件。Warnings may be generated if the destination filesystem doesn't permit chown() or chmod() system calls to be made on files — for example, if the destination filesystem is a FAT filesystem.

范例

Example #1 rename() 例子

<?php
rename
("/tmp/tmp_file.txt""/home/user/login/docs/my_file.txt");
?>

参见

User Contributed Notes

lord dot dracon at gmail dot com 03-Jan-2018 11:14
rename() function apparently doesn't move files larger than 4 GB, even though the filesystem supports, when the operating system is 32 bits.

Tested here with PHP 5.5.9 (x86), in Linux environment (Ubuntu 14.04.5 LTS i686), with source file (60 GB RAR file) in ext4 filesystem and destination is a external HD with NTFS filesystem. Only 4 GB was copied and RAR was corrupted: "Unexpected end of archive".

Not tested if rename() can move files larger than 4 GB in 64-bit environment.
tomv 10-Mar-2017 02:31
If $oldname and $newname are existing hard links referring to the same file, then rename() does nothing, and returns a success status.
(from the underlying libc rename() manual)
On the other hand "/bin/mv oldname newname" results in the removal of "oldname".
ben at indietorrent dot org 02-Jul-2015 03:31
From the Changelog notes:

"Warnings may be generated if the destination filesystem doesn't permit chown() or chmod() system calls to be made on files — for example, if the destination filesystem is a FAT filesystem."

More explicitly, rename() may still return (bool) true, despite the warnings that result from the underlying calls to chown() or chmod(). This behavior can be misleading absent a deeper understanding of the underlying mechanics. To rename across filesystems, PHP "fakes it" by calling copy(), unlink(), chown(), and chmod() (not necessarily in that order). See PHP bug #50676 for more information.

On UNIX-like operating systems, filesystems may be mounted with an explicit uid and/or gid (for example, with mount options "uid=someuser,gid=somegroup"). Attempting to call rename() with such a destination filesystem will cause an "Operation not permitted" warning, even though the file is indeed renamed and rename() returns (bool) true.

This is not a bug. Either handle the warning as is appropriate to your use-case, or call copy() and then unlink(), which will avoid the doomed calls to chown() and chmod(), thereby eliminating the warning.
mike at mbfisher dot com 23-Jan-2015 09:31
[Editor note: this works because SplFileObject has the __toString() method which returns the file path]

Note that you can pass an SplFileInfo object as either argument:

<?php
# Assume a file 'foo' in the current directory

rename('foo', new SplFileInfo('bar'));

# foo is now bar!

rename(new SplFileInfo('bar'), 'foo');

# bar is now foo again
?>
Robert 27-Jun-2014 08:38
If you use SplFileObject for the same file which
you want to rename you have to remove SplFileObject objec first.

<?php

$filePath
= 'testFile.txt';
$fileObj = new SplFileObject$filePath  );
rename( $filePath, 'newName.txt'  );

// You will get - Permission denied error

$filePath = 'testFile.txt';
$fileObj = new SplFileObject( 'filePath.txt' );
$fileObj = null;
rename( $filePath, 'newName.txt'  );

// and now it is working.
?>
mike 19-Dec-2013 11:35
Important note - rename() does NOT work for *directories* across filesystems or devices. Only *files*

You will get two warnings:
"PHP Warning:  rename(): The first argument to copy() function cannot be a directory in <whatever> on line <whatever>"
"PHP Warning:  rename(t2,/var/run/test/t2): Invalid cross-device link in <whatever> on line <whatever>"

The copy() mentioned I assume is C's copy() and not PHP's copy() function. There is an associated bug in the Ubuntu bug system for this as well, that was escalated to bugs.php.net:
https://bugs.php.net/bug.php?id=54097

The only workarounds right now I believe is using PHP copy($source, $dest) and then on success, PHP unlink($source), or doing system("mv $source $dest") which is hokey, and should be surrounded by quotes for paths with spaces or other shell metacharacters, and possibly escaped for security.
bcag2 at free dot fr 07-Mar-2013 03:39
on windows (XP, vista, 7...) http://fr.wikipedia.org/wiki/Windows-1252", if your file name contains accent, it doesn't work basically. So use iconv function to convert from utf-8 to cp1252 as bellow :
<?php
 
$nomfichierinitial
=iconv("UTF-8", "CP1252", "C:\\wamp\\www\\tést.txt");
$nomfichierfinal="C:\\wamp\\www\\test.txt";
rename($nomfichierinitial, $nomfichierfinal);
?>
Martin Pelletier 05-Feb-2011 10:01
rename() is working on Linux/UNIX but not working on Windows on a directory containing a file formerly opened within the same script. The problem persists even after properly closing the file and flushing the buffer.

<?php
$fp
= fopen ("./dir/ex.txt" , "r+");
$text = fread($fp, filesize("../dir/ex.txt"));
ftruncate($fp, 0);
$text2 = "some value";
fwrite ($fp$text2 );
fflush($fp);
fclose ($fp);
if (
is_resource($fp))
   
fclose($fp);
rename ("./dir", ".dir2"); // will give a ?permission denied? error
?>

Strangely it seem that the rename command is  executed BEFORE the handle closing on Windows.

Inserting a sleep() command before the renaming cures the problem.

<?php
$fp
= fopen ("./dir/ex.txt" , "r+");
$text = fread($fp, filesize("../dir/ex.txt"));
ftruncate($fp, 0);
$text2 = "some value";
fwrite ($fp$text2 );
fflush($fp);
fclose ($fp);
if (
is_resource($fp))
   
fclose($fp);
sleep(1);    // this does the trick
rename ("./dir", ".dir2"); //no error
?>
andrew at 21cv dot co dot uk 15-Apr-2010 05:19
Code first, then explanation.

<?php

 rename
("/folder/file.ext", "newfile.ext");

?>

That doesn't rename the file within the folder, as you might assume, instead, it moves the file to whatever the PHP working directory is... Chances are you'll not find it in your FTP tree. Instead, use the following:

<?php

 rename
("/folder/file.ext", "/folder/newfile.ext");

?>
Morteza 10-Apr-2010 12:04
This code renames all  files and folders in a specific directory to lower case:

<?php
$path
= "my_doc";

function
getDirectory( $path = '.', $level = 0 ){

   
$ignore = array( 'cgi-bin', '.', '..' );

   
$dh = @opendir( $path );
   
    while(
false !== ( $file = readdir( $dh ) ) )
    {
        if( !
in_array( $file, $ignore ) )
        {
           
$spaces = str_repeat( '&nbsp;', ( $level * 4 ) );
            if(
is_dir( "$path/$file" ) )
            {
                echo
"<strong>$spaces $file</strong><br />";
               
rename($path."\\".$file, strtolower($path."\\".$file));
               
getDirectory( "$path/$file", ($level+1) );
               
            }
            else {
                echo
"$spaces $file<br />";
               
rename($path."\\".$file, strtolower($path."\\".$file));
            }
        }  
    }
   
closedir( $dh );
}

getDirectory( $path , 0 )

?>
pcdinh at phpvietnam dot net 29-Jul-2009 09:10
For those who are still confused about the behavior of rename() in Linux and Windows (Windows XP) when target destination exists:

I have tested rename($oldName, $targetName) in PHP 5.3.0 and PHP 5.2.9 on both OS and find that if a file named $targetName does exist before, it will be overwritten with the content of $oldName
andrew at iwebsolutions dot co dot uk 02-Apr-2009 01:36
Note that this WILL NOT WORK if trying to rename a directory to a network share.

e.g.
rename('/home/user/me/dir1', '/mnt/shares/nfsmount/dir2')

will create a file called 'dir2' on the share and not a directory.

This caught me out and my (quickest) solution was to use an exec and mv command:

<?php
$cmd
= 'mv "/home/user/me/dir1" "/mnt/shares/nfsmount/dir2"';
exec($cmd, $output, $return_val);

if (
$return_val == 0) {
   echo
"success";
} else {
   echo
"failed";
}
?>
Whooptydoo 07-Jul-2008 09:11
If by any chance you end up with something equivalent to this:

<?php
rename
('/foo/bar','/foo/bar');
?>

It returns true. It's not documented.
dev at islam-soft dot com 05-Jan-2007 04:52
- rename extension of files

changeext($directory, $ext1, $ext2, $verbose)

i wrote this function to rename the extention of some files in a folder and sub-folders inside it ..

parameter 1 :  the directory name
parameter 2 :  the first extention wich we want to replace
parameter 3 :  the new extention of files

for a simple usage call the function :
changeext('dir', 'html', 'php',  'false');

to change evry file name with extention html  into php  in the directory  dir

<?php

function changeext($directory, $ext1, $ext2, $verbose = false) {
 
$num = 0;
  if(
$curdir = opendir($directory)) {
   while(
$file = readdir($curdir)) {
     if(
$file != '.' && $file != '..') {

      
$srcfile = $directory . '/' . $file;
      
$string  = "$file";
      
$str     = strlen($ext1);
      
$str++;
      
$newfile = substr($string, 0, -$str);
      
$newfile = $newfile.'.'.$ext2;
      
$dstfile = $directory . '/' . $newfile;

       if (
eregi("\.$ext1",$file)) { # Look at only files with a pre-defined extension
      
$fileHand = fopen($srcfile, 'r');
      
fclose($fileHand);
      
rename($srcfile, $dstfile );
       }

       if(
is_dir($srcfile)) {
        
$num += changeext($srcfile, $ext1, $ext2, $verbose);
       }
     }
   }
  
closedir($curdir);
  }
  return
$num;
}

changeext('dir', 'html', 'php''false');

?>

to remove the extention of files , just leave the parameter $ext2 blank ''
Eric (Themepark.com) 03-Nov-2006 10:31
This was a fun one-- on Win XP, rename throws a "permission deined" if you try to rename across volumes.. i.e. rename("c:\windows\temp\x.txt", "g:\destination") will fail.
David Thole (root at thedarktrumpet.com) 22-Oct-2006 12:20
As of PHP 5.1.4 compiled on a mac, using rename with spaces one should just use the space.   Take for example:

rename("/tmp/somefile.tar", "/mnt/laptop storage/somefile.tar");

If you use the backslash, like if you were cd-ing to the directory, rename will fail.  Example:

rename("/tmp/somefile.tar", "/mnt/laptop\ storage/somefile.tar");

While not really a bug, it did confuse me for a little bit while working on a backup script.
PHP at Drarok dot com 08-Aug-2006 01:57
As described from the unlink() page:
You have to release any handles to the file before you can rename it (True on Windows, at least).
This will NOT work, you'll receive permission denied errors:
<?php
    $fileHand
= fopen('tempFile.txt', 'r');
   
rename( 'tempFile.txt', 'tempFile2.txt' ); // Permission Denied!
?>

Simply close the handle to fix this:
<?php
    $fileHand
= fopen('tempFile.txt', 'r');
   
fclose($fileHand);
   
rename( 'tempFile.txt', 'tempFile2.txt' );
?>

This has me scratching my head for some time, as the handle was opened at the top of a marge function, and the rename was at the bottom.
php at froghh dot de 19-Jan-2006 03:00
Remark for "php at stock-consulting dot com"'s note:
This depends on the operating system.
On windows-systems you can't rename a file to an existing destination (ok, with tools you can - but they unlink the exisiting one before).
php at stock-consulting dot com 04-Jan-2006 02:36
rename() fails with PHP4 and PHP5 under Windows if the destination file exists, regardless of file permission settings. I now use a function similar to that of ddoyle [at] canadalawbook [dot] ca, which first tries rename(), checks if it returned FALSE and then uses copy()/unlink() if it failed.

However, copy() is, unlike rename(), NOT useable for "atomic updates". Another process may actually access the destination file while copy() is working. In such a case, the other process with perceive the file as empty or with incomplete content ("half written").
php-public at macfreek dot nl 18-Dec-2005 11:33
It is unclear what encoding the arguments of rename should have; For PHP 4.3, on a HFS+ filesystems, rename() did not handle UTF-8 strings, and returned an error.
tbrillon at gmail dot com 14-Sep-2005 01:27
I needed to move a file to another folder regardless if that file existed in the target already so I wrote a small piece to append a unique number to each file.

$rem = $_GET['file'];
$ticket = uniqid(rand(), true);

rename("$rem", "www/home/storefile/$ticket$rem");

the output looks like this - 6881432893ad4925a1.70147481filename.txt

This also helps if you want different versions of the file stored.
ddoyle [at] canadalawbook [dot] ca 07-Sep-2005 03:35
rename() definitely does not follow the *nix rename convention on WinXP with PHP 5.  If the $newname exists, it will return FALSE and $oldname and $newname will remain in their original state.  You can do something like this instead:

function rename_win($oldfile,$newfile) {
   if (!rename($oldfile,$newfile)) {
      if (copy ($oldfile,$newfile)) {
         unlink($oldfile);
         return TRUE;
      }
      return FALSE;
   }
   return TRUE;
}
tomfelker at gmail dot com 11-Aug-2005 02:51
Actually, I'm pretty sure that rename follows the convention of *nix rename(2) in overwriting the destination if it exists atomically (meaning that no other process will see the destination cease to exist, even for an instant).  This is useful because it allows you to build a file as a temp file, then rename it to where you want it to be, and nobody sees the file when it's half done.

Probably rename($old, $new) with an existing new was caused by permission problems.  I bet the other problems you had were the result of not calling clearstatcache(), which can cause PHP to act like a file exists though it has since been deleted.
sophie at sitadelle dot com 14-Nov-2003 08:22
Hello!
For unix/linux users: it is usefull to know that if you use rename() for a directory, the new one will be created with the current umask!
pearcec at commnav dot com 15-Jun-2001 01:17
If you rename one directory to another where the second directory exists as an empty directory it will not complain.

Not what I expected.

[pearcec@abe tmp]$ mkdir test1
[pearcec@abe tmp]$ mkdir test2
[pearcec@abe tmp]$ touch test1/test
[pearcec@abe tmp]$ php
<?php
rename
("test1","test2");
?>
X-Powered-By: PHP/4.0.5
Content-type: text/html

[pearcec@abe tmp]$ ls -al
total 12
drwxr-xr-x    3 pearcec  commnav      4096 Jun 15 13:17 .
drwxr-xr-x   18 pearcec  commnav      4096 Jun 15 13:15 ..
drwxr-xr-x    2 pearcec  commnav      4096 Jun 15 13:16 test2
[pearcec@abe tmp]$ ls -la test2/
total 8
drwxr-xr-x    2 pearcec  commnav      4096 Jun 15 13:16 .
drwxr-xr-x    3 pearcec  commnav      4096 Jun 15 13:17 ..
-rw-r--r--    1 pearcec  commnav         0 Jun 15 13:16 test
[pearcec@abe tmp]$
michael-nospam at sal dot mik dot hyperlink dot net dot au 24-Nov-1999 11:43
Note, that on Unix, a rename is a beautiful way of getting atomic updates to files.

Just copy the old contents (if necessary), and write the new contents into a new file, then rename over the original file.

Any processes reading from the file will continue to do so, any processes trying to open the file while you're writing to it will get the old file (because you'll be writing to a temp file), and there is no "intermediate" time between there being a file, and there not being a file (or there being half a file).

Oh, and this only works if you have the temp file and the destination file on the same filesystem (eg. partition/hard-disk).