To rename a file from one name to another using php, the easiest way is to use the php rename() function.


Renaming files with php is easy. We can use the php rename() function to rename files and rename directories.

If we want to rename a file named “old_file_name.txt” to “new_file_name.txt”, we can do this with the following php code:


We can also move the file from one folder to another and rename the file if we want. If we want to move the file from “folder1” to “folder2”, and rename the file, we can do this with the following php code:


If we want to rename a directory named “old_folder_name” to “new_folder_name”, we can do so with the following php code:


Renaming Multiple Files with php

In php, it is easy to rename multiple files in a folder. To do so, we can use the php rename() function in a loop.

Let’s say we have 5 files and we want to rename these 5 files.

We can put the 5 file names in an array, define a new array with the 5 new file names, and then loop over that array calling the rename() function inside the loop:

$files_to_rename = array("file1.php","file2.php","file3.php","file4.php","file5.php");

$new_file_names = array("file1_new.php","file2_new.php","file3_new.php","file4_new.php","file5_new.php");

for ($x = 0; $x < 5; $x++) {
  rename("./folder/" . $files_to_rename[$x], "./folder/" . $new_file_names[$x]);

With this code, the 5 files will all be renamed.

Renaming a Directory with php

We can also rename directories with the rename() function.

Let's say we want to rename the folder named "edits_done" folder to a different folder named "production".

We can move the directory easily with the php rename() function in the following php code:


Hopefully this article has been helpful for you to understand how you rename a file, rename a directory and rename multiple files using php.

Categorized in:


Last Update: February 26, 2024