How to rename a file or directory in 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
1 | 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
.
1 2 3 4 5 6 7 8 9 10 | <?php $oldname = './file.txt'; $newname = './newfile.txt'; 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
.
1 2 3 4 5 6 7 8 9 10 | <?php $oldname = './images'; $newname = './uploads’; 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.
1 2 3 4 5 6 7 8 9 10 | <?php $oldname = './file.txt'; $newname = './pages/file.txt'; 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..!!