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.
bool rename ( string $source , string $target )
Returns TRUE on success, and FALSE on failure.
Here are examples of how to use the rename() function to rename files and directories:
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!".
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!".
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.