PHP rename() Function: Syntax, Parameters, Return Value, Examples, and Usage Notes
This article explains PHP's rename() function, detailing its syntax, required source and target parameters, boolean return values, practical code examples for renaming files and directories, and important considerations such as permissions and error handling.
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 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 destination file or directory.
Return Value
Returns TRUE on success and FALSE on failure.
Examples
Below are examples demonstrating how to use rename() to rename files and directories.
Renaming 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!";
}
?>Renaming 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!";
}
?>Notes
The rename() function may be limited by file system permissions; ensure you have sufficient rights to change names. If the source file or directory does not exist, rename() will return FALSE , indicating failure.
Summary
The rename() function is a powerful PHP tool for renaming files or directories by simply specifying the source and target names; the provided example code demonstrates its usage in typical PHP projects.
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.