Welcome to the PHP rename() Function tutorial! Today, we're going to explore how to rename files and directories in PHP. This function is useful for various tasks, such as renaming uploaded files, managing backups, or automating file organization. π Note: This tutorial is designed for beginners and intermediates, so let's dive right in!
In PHP, the rename() function changes the name of a file or a directory. The syntax is as follows:
bool rename ( string old_name , string new_name )The function takes two arguments:
old_name: The original name of the file or directory you want to rename.new_name: The new name you want to give to the file or directory.The function returns TRUE if the renaming was successful and FALSE if it wasn't.
Let's rename an image uploaded by a user in a simple web application.
// Get the uploaded image
$old_name = $_FILES['image']['name'];
// Generate a unique new name
$new_name = uniqid() . '_' . $old_name;
// Move and rename the uploaded image
if (move_uploaded_file($_FILES['image']['tmp_name'], $new_name)) {
echo "Image uploaded and renamed successfully.";
} else {
echo "Error: Image not uploaded.";
}Renaming a directory is similar to renaming a file. Just keep in mind that you should provide the full path to both the old directory and the new directory.
$old_dir = '/path/to/old_dir';
$new_dir = '/path/to/new_dir';
if (rename($old_dir, $new_dir)) {
echo "Directory renamed successfully.";
} else {
echo "Error: Directory not renamed.";
}is_file() and is_dir() functions to check if the file or directory exists before renaming.What does the PHP `rename()` function do?
Let's create a script that moves and renames all .txt files from one directory to another.
$source_dir = '/path/to/source_dir';
$destination_dir = '/path/to/destination_dir';
if (is_dir($source_dir)) {
$files = scandir($source_dir);
foreach ($files as $file) {
if (strpos($file, '.txt') !== false) {
$new_name = basename($file, '.txt') . '_backup.txt';
$source_file = $source_dir . '/' . $file;
$destination_file = $destination_dir . '/' . $new_name;
if (rename($source_file, $destination_file)) {
echo "File {$file} renamed as {$new_name}.<br>";
} else {
echo "Error: File {$file} not renamed.<br>";
}
}
}
}In this example, we first check if the source directory exists. If it does, we scan the directory for all files and check if they have the .txt extension. If they do, we generate a new name, move the file, and rename it.
That's all for the PHP rename() Function tutorial! I hope this lesson was helpful in understanding how to rename files and directories in PHP. If you have any questions, feel free to ask! π