The rename()
function in PHP renames an existing file or directory.
rename(string $oldname, string $newname, resource $context = ?): bool
oldname
: This specifies the old name of the file or directory we want to rename.
newname
: This specifies the new name of a file or directory.
context
: This is an optional parameter that is a set of options able to alter the behavior of a stream.
rename()
returns true
if the name is successfully changed. Otherwise, in case of any error, it returns false
.
Note:
- If a file is being renamed and the
newname
specified already exists, the file is overwritten.- If a directory is being renamed and the
newname
specified already exists as a directory, a warning is produced.
The following code shows how to use the rename()
function.
<?phpecho "contents of task1.txt:\n";readfile("task1.txt");echo "\ncontents of task2.txt: \n";readfile("task2.txt");rename("task1.txt","task2.txt");echo "\nAfter rename: ";readfile("task2.txt");?>
In the code above, there are two text files, task1.txt
and task2.txt
, and their content is displayed.
Ttask1.txt
is renamed to task2.txt
, but since task2.txt
already exists, it overwrites the original file. Then, when the content of task2.txt
is read, the content is the same as task1.txt
.
Free Resources