Current Location: Home> Latest Articles> PHP rename() Function Explained: How to Rename Files and Directories

PHP rename() Function Explained: How to Rename Files and Directories

M66 2025-06-12

PHP rename() Function Explained: How to Rename Files and Directories

In PHP, the rename() function is used to rename files or directories. It provides a simple way to change the name of a file or directory. Whether it's a single file or an entire directory, this function can be used to rename them. By specifying the source file or directory's name and the target name, the renaming process is easily accomplished.

Syntax:

bool rename(string $source, string $target)

In the example above, we rename a file called "old_file.txt" to "new_file.txt". If the renaming is successful, "File renamed successfully!" will be displayed, otherwise "File renaming failed!" will be shown.

Renaming a directory:


<?php
$old_name = "old_directory";
$new_name = "new_directory";

if (rename($old_name, $new_name)) {
    echo "Directory renamed successfully!";
} else {
    echo "Directory renaming failed!";
}
?>

In this example, we rename a directory called "old_directory" to "new_directory". If the renaming is successful, "Directory renamed successfully!" will be displayed, otherwise "Directory renaming failed!" will be shown.

Important Notes:

  • The rename() function may be restricted by file system permissions. Ensure you have sufficient permissions to rename the file or directory.
  • If the source file or directory does not exist, the rename() function will return FALSE, indicating a failure to rename.

Conclusion:

The rename() function in PHP is a powerful tool for renaming files or directories. It allows you to easily change the name of a file or directory by specifying both the source and target names. With the provided example code, you can quickly understand how to use the rename() function in your PHP projects to perform file and directory renaming operations.