How to Rename a File in PHP: Simple Guide with Examples
In PHP, you can rename a file using the
rename() function by providing the current file name and the new file name as arguments. This function moves the file to the new name or location if successful.Syntax
The rename() function takes two parameters: the current file path and the new file path. It returns true if the file was renamed successfully, or false if it failed.
- oldname: The current name or path of the file.
- newname: The new name or path you want the file to have.
php
bool rename ( string $oldname , string $newname )
Example
This example shows how to rename a file named oldfile.txt to newfile.txt. It checks if the rename was successful and prints a message.
php
<?php $oldName = 'oldfile.txt'; $newName = 'newfile.txt'; if (rename($oldName, $newName)) { echo "File renamed from $oldName to $newName successfully."; } else { echo "Failed to rename file."; } ?>
Output
File renamed from oldfile.txt to newfile.txt successfully.
Common Pitfalls
- Trying to rename a file that does not exist will cause
rename()to returnfalse. - Not having the right permissions to rename the file will cause failure.
- Using relative paths incorrectly can cause the function to fail.
- Renaming across different file systems or drives may not work as expected.
Always check the return value and handle errors gracefully.
php
<?php // Wrong: file does not exist if (!rename('missing.txt', 'newname.txt')) { echo "Error: File does not exist or cannot be renamed."; } // Right: check file exists first $oldName = 'file.txt'; $newName = 'renamed.txt'; if (file_exists($oldName)) { if (rename($oldName, $newName)) { echo "File renamed successfully."; } else { echo "Failed to rename file due to permissions or other issues."; } } else { echo "File does not exist."; } ?>
Output
Error: File does not exist or cannot be renamed.
Quick Reference
| Function | Description | Return Value |
|---|---|---|
| rename(oldname, newname) | Renames or moves a file from oldname to newname | true on success, false on failure |
| file_exists(filename) | Checks if a file exists before renaming | true if file exists, false otherwise |
| is_writable(filename) | Checks if file is writable (permission check) | true if writable, false otherwise |
Key Takeaways
Use the rename() function with old and new file names to rename files in PHP.
Always check if the file exists and handle the return value of rename() to catch errors.
File permissions and correct file paths are essential for successful renaming.
rename() can also move files if the new name includes a different path.
Avoid renaming files across different file systems as it may fail.