Clue Mediator

How to rename a file or directory in PHP

šŸ“…October 8, 2020
šŸ—PHP

In this article, we will explain to you how to rename a file or directory in PHP. It's a very easy way to rename a file or directory in PHP.

Using the built-in rename() function, we can rename a file or directory. If the new name already exists, then the `rename()` function will overwrite it. Using this function we can also move a file to a different directory.

Similar article:

This function requires two arguments: the first is the name of the file you want to rename and the second is the new name of the file. This function returns true on success otherwise false.

Syntax

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

Parameters

  • $oldname: It specifies the file or directory name which you want to rename.
  • $newname: It specifies the new name of the file or directory.
  • $context: This is an optional parameter. It specifies the behaviour of the stream.

Example 1: Rename file name

In the following example, we will see how to rename a file named `file.txt` to `newfile.txt`.

<!--?php
$oldname = './file.txt';
$newname = './newfile.txt';<p-->

if(rename($oldname, $newname)){
   echo "File has been renamed";
} else {
   echo "Fail to rename file";
}
?>

Example 2: Rename directory name

Letā€™s take a next example where we will see how to rename a directory named `images` to `uploads`.

<!--?php
$oldname = './images';
$newname = './uploadsā€™;<p-->

if(rename($oldname, $newname)){
   echo "Directory has been renamed";
} else {
   echo "Fail to rename directory";
}
?>

Example 3: Use the rename function to move a file

In this last example, weā€™ll see how to move a file named `file.txt` to `pages` directory using `rename()` function.

<!--?php
$oldname = './file.txt';
$newname = './pages/file.txt';<p-->

if(rename($oldname, $newname)){
   echo "File has been moved";
} else {
   echo "Fail to move file";
}
?>

Note: If a file or directory does not exist then `rename()` function will throw a warning so it is a good practise to check if a file exists or not using the file_exists() function before rename the file or directory.

Thatā€™s it for today.
Thank you for reading. Happy Coding..!!