Master PHP’s rename() Function: Rename Files & Directories with Ease
This guide explains PHP's rename() function, covering its syntax, parameters, return values, practical code examples for renaming both files and directories, and important considerations such as permissions and error handling, enabling developers to manage filesystem objects efficiently.
Introduction
The rename() function in PHP is used to rename files or directories, providing a straightforward way to change their names by specifying the source and target names.
Syntax
bool rename ( string $source , string $target )Parameters
$source: required, the name of the source file or directory. $target: required, the name of the target file or directory.
Return Value
Returns TRUE on success, FALSE on failure.
Examples
Rename a file
<?php
$old_name = "old_file.txt";
$new_name = "new_file.txt";
if (rename($old_name, $new_name)) {
echo "File renamed successfully!";
} else {
echo "File rename failed!";
}
?>This script renames old_file.txt to new_file.txt and outputs a success or failure message.
Rename a directory
<?php
$old_name = "old_directory";
$new_name = "new_directory";
if (rename($old_name, $new_name)) {
echo "Directory renamed successfully!";
} else {
echo "Directory rename failed!";
}
?>This script renames old_directory to new_directory with similar success/failure feedback.
Notes
The rename() function may be restricted by filesystem permissions; ensure you have sufficient rights. If the source file or directory does not exist, rename() returns FALSE .
Summary
The rename() function is a powerful PHP tool for renaming files or directories by specifying source and target names, and the provided examples demonstrate its usage for both files and directories.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
