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

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.

Example 2: Rename directory name

Let’s take a next example where we will see how to rename a directory named images to uploads.

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.

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..!!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *