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

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

M66 2025-06-12

PHP rename() Function Introduction

In PHP, the rename() function is used to rename files or directories. It provides a simple method to change the name of a file or directory. Whether it's a single file or an entire directory, you can easily rename it using this function by specifying the source and target names.

Syntax

bool rename ( string $source , string $target )

Parameter Explanation:

  • $source: Required. Specifies the name of the source file or directory to be renamed.
  • $target: Required. Specifies the new name for the file or directory.

Return Value:

Returns TRUE on success, and FALSE on failure.

Example Code

Here are examples of how to use the rename() function to rename files and directories:

Example 1: Renaming a File

This example shows how to rename a file from "old_file.txt" to "new_file.txt".

<?php
$old_name = "old_file.txt";
$new_name = "new_file.txt";

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

In the above example, we used the rename() function to rename the file. If successful, the output will be "File renamed successfully!"; otherwise, it will display "File rename failed!".

Example 2: Renaming a Directory

This example demonstrates how to rename a directory from "old_directory" to "new_directory".

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

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

In this example, we used the rename() function to rename the directory from "old_directory" to "new_directory". If successful, the output will be "Directory renamed successfully!"; otherwise, it will show "Directory rename failed!".

Important Notes

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

Conclusion

The rename() function in PHP is a powerful tool for renaming files or directories. It allows you to change the name of a file or directory by simply specifying the source and target names. By mastering this function, you can easily perform file and directory renaming operations in your PHP projects.