
You can rename a directory in PHP using the rename()
function. Here is the basic syntax:
Syntax:
rename('old_directory_name', 'new_directory_name');
✅ Example 1: Rename a Directory
<?php
$oldName = 'old_folder';
$newName = 'new_folder';
if (rename($oldName, $newName)) {
echo "Directory renamed successfully!";
} else {
echo "Error: Unable to rename directory.";
}
?>
✅ Example 2: Check if Directory Exists Before Renaming
<?php
$oldName = 'old_folder';
$newName = 'new_folder';
if (is_dir($oldName)) {
if (!file_exists($newName)) {
if (rename($oldName, $newName)) {
echo "Directory renamed successfully!";
} else {
echo "Error: Failed to rename.";
}
} else {
echo "Error: New directory name already exists.";
}
} else {
echo "Error: Old directory does not exist.";
}
?>
✅ Permissions Consideration
Ensure the script has write permissions on both the old and new directory paths.
chmod -R 775 old_folder
✅ Rename Directory Across Different Paths
<?php
$oldPath = '/var/www/html/old_folder';
$newPath = '/var/www/html/new_folder';
if (rename($oldPath, $newPath)) {
echo "Directory moved and renamed successfully!";
} else {
echo "Error: Unable to move and rename directory.";
}
?>
✅ Common Errors and Fixes
- Directory not found – Ensure the path exists and is correct.
- Permission issues – Grant appropriate permissions using
chmod
. - Target directory exists – Ensure the new directory name is unique.
Would you like help with more advanced directory handling? 🚀