The rename() function in PHP is a built-in function used to rename files or directories. It attempts to change the old name of a file or directory with a new name specified by the user, and can move between directories if necessary.
If the new name specified by the user already exists, the rename() function will overwrite it. The old name of the file and the new user-specified name are sent as parameters to the rename() function, which returns True on success and False on failure.
Syntax:
rename(oldname, newname, context)
Usage of parameters:
The rename() function in PHP accepts three parameters.
oldname: It is a mandatory parameter that specifies the old name of the file or directory.
newname: It is a mandatory parameter that specifies the new name of the file or directory.
context: It is an optional parameter that specifies the behavior of the stream.
Return value:
Returns True when successful and False when failed.
Errors and Exceptions
1. When renaming a directory, rename will generate a warning if the new name already exists.
2.The wrapper used in oldname must match the wrapper used in newname.
3. If the target file system does not allow the chown() or chmod() system call to be executed on the file, the rename() function may generate a warning.
The following program demonstrates the rename() function.
Suppose there is a file named "gfg.txt"
Code Example 1:
<?php $old_name = "gfg.txt" ; $new_name = "newgfg.txt" ; rename( $old_name, $new_name) ; ?>
Output:
1
Code example 2:
<?php $old_name = "gfg.txt" ; $new_name = "newgfg.txt" ; // 检查文件是否已经存在 if(file_exists($new_name)) { echo "重命名$old_name时出错" ; } else { if(rename( $old_name, $new_name)) { echo "成功地将 $old_name 重命名为 $new_name" ; } else { echo "具有相同名称的文件已经存在" ; } } ?>
Output:
成功地将gfg.txt重命名为newgfg.txt
Related recommendations: "PHP Tutorial"
The above is the detailed content of Detailed explanation of the use of PHP rename function (php rename files). For more information, please follow other related articles on the PHP Chinese website!