PHP rename( ) Function (original) (raw)
Last Updated : 23 Sep, 2024
The rename() function in PHP is an inbuilt function that is used to rename a file or directory. It attempts to change an old name of a file or directory with a new name specified by the user and it may move between directories if necessary. If the new name specified by the user already exists, the rename() function overwrites it. The old name of the file and the new name specified by the user are sent as parameters to the rename() function and it returns a True on success and a False on failure.
**Syntax:
rename(oldname, newname, context)
**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:
- It returns a True on success and a False on failure.
**Errors And Exception
- The rename() function generates a Warning if the newname already exists while renaming a directory.
- The wrapper used in oldname must match the wrapper used in newname.
- If the destination filesystem doesn’t permit chown() or chmod() system calls to be made on files, then rename() function may generate Warnings.
**Examples:
Input : $old_name = "gfg.txt" ;
$new_name = "newgfg.txt" ;
rename( newname,new_name, newname,old_name) ;
Output : 1
Input : $old_name = "gfg.txt" ;
$new_name = "newgfg.txt" ;
if(file_exists($new_name))
{
echo "Error While Renaming $old_name" ;
}
else
{
if(rename( oldname,old_name, oldname,new_name))
{
echo "Successfully Renamed oldnametoold_name to oldnametonew_name" ;
}
else
{
echo "A File With The Same Name Already Exists" ;
}
}
Output : Successfully Renamed gfg.txt to newgfg.txt
Example of rename() Function
Below programs illustrate the rename() function. Suppose there is a file named “gfg.txt”
**Example 1: Thisexample shows the basic usage of the rename() function. It attempts to rename a file named gfg.txt to newgfg.txt. If successful, it returns 1 (True), otherwise, it returns 0 (False).
php `
oldname,old_name, oldname,new_name) ; ?>`
**Output:
1
**Example 2: In this example, we check if a file with the new name already exists. If it does, an error message is displayed. If not, the program attempts to rename the file and displays a success or failure message based on the outcome.
php `
oldname,old_name, oldname,new_name)) { echo "Successfully Renamed oldnametoold_name to oldnametonew_name" ; } else { echo "A File With The Same Name Already Exists" ; } } ?>`
**Output:
Successfully Renamed gfg.txt to newgfg.txt
**Related Articles: