In PHP, renaming a file can be done using the rename() function. This function allows you to change the name of a file or move it to a different directory by specifying a new name or path.
Syntax of the rename() Function
php
Copy code
rename(old_name, new_name)
- old_name: The current name (or path) of the file.
- new_name: The new name (or new path) for the file.
The rename() function returns TRUE on success and FALSE on failure.
Basic Example of Renaming a File
Let’s say you have a file named “old_file.txt” and you want to rename it to “new_file.txt”.
php
Copy code
<?php
$oldName = “old_file.txt”;
$newName = “new_file.txt”;
if (rename($oldName, $newName)) {
echo “File renamed successfully.”;
} else {
echo “Failed to rename the file.”;
}
?>
In this example:
- The rename() function changes “old_file.txt” to “new_file.txt”.
- If successful, it outputs “File renamed successfully”; otherwise, it outputs an error message.