Home > Backend Development > PHP Tutorial > Detailed explanation of the use of PHP rename function (php rename files)

Detailed explanation of the use of PHP rename function (php rename files)

藏色散人
Release: 2023-04-06 08:12:01
Original
8168 people have browsed it

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)
Copy after login

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) ; 
  
?>
Copy after login

Output:

1
Copy after login

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 "具有相同名称的文件已经存在" ; 
     } 
  } 
?>
Copy after login

Output:

成功地将gfg.txt重命名为newgfg.txt
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template