百科狗-知识改变命运!
--

rename() - 重命名一个文件或目录 - php 文件目录函数

百变鹏仔1年前 (2023-11-21)阅读数 22#技术干货
文章标签文件

rename()

rename() - 重命名一个文件或目录 - php 文件目录函数

(PHP 4, PHP 5, PHP 7)

重命名一个文件或目录

说明

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

尝试把$oldname重命名为$newname。

参数

$oldnameNote:

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

新的名字。

$context

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

返回值

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

更新日志

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

范例

Example #1rename()例子

参见

  • copy() 拷贝文件
  • unlink() 删除文件
  • move_uploaded_file() 将上传的文件移动到新位置
Code first, then explanation.

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: 
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.
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.
If by any chance you end up with something equivalent to this:

It returns true. It's not documented.
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).
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
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.

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. 
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").
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).
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  on line "
"PHP Warning: rename(t2,/var/run/test/t2): Invalid cross-device link in  on line "
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.
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.
- 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

to remove the extention of files , just leave the parameter $ext2 blank ''
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!
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.
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 : 
If you use SplFileObject for the same file which
you want to rename you have to remove SplFileObject objec first. 
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.
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.
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: 
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:

Simply close the handle to fix this:

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.
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.
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".
[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: 
This code renames all files and folders in a specific directory to lower case: 

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)