Using PHP rename() to Rename Files and Directories
This article explains PHP's rename() function, detailing its syntax, parameters, return values, and provides example code for renaming both files and directories, along with important usage considerations, including error handling and permission requirements.
Introduction: In PHP, the rename() function is used to rename files or directories, providing a simple way to change their names by specifying the source and target.
Syntax: bool rename ( string $source , string $target ) Parameters: $source (required) – the name of the source file or directory; $target (required) – the desired new name.
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!";
}
?>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!";
}
?>Note: The rename() function may be limited by filesystem permissions; ensure you have sufficient rights and that the source exists, otherwise the function returns FALSE.
Summary: The rename() function is a powerful PHP tool for renaming files and directories, allowing developers to change names by specifying source and target paths, as demonstrated in the example code.
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.
