What are some best practices for iterating through directories and renaming files in PHP?
When iterating through directories and renaming files in PHP, it is important to handle errors, check if a file is a directory, and use functions like opendir(), readdir(), and rename() to efficiently rename files. Additionally, it is recommended to use a recursive function to handle subdirectories if needed.
<?php
function renameFilesInDirectory($directory) {
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$oldName = $directory . '/' . $file;
$newName = $directory . '/new_' . $file;
if (!is_dir($oldName)) {
rename($oldName, $newName);
} else {
renameFilesInDirectory($oldName);
}
}
}
closedir($handle);
}
}
// Usage
renameFilesInDirectory('/path/to/directory');
?>