PHP rename() Function: Syntax, Parameters, Return Values, Usage Example, and Precautions
The PHP rename() function allows renaming or moving files and directories, with syntax rename(string $oldname, string $newname, resource $context = null): bool, detailed parameter descriptions, return values, example code, and important usage notes such as overwriting behavior, cross‑filesystem limitations, and permission checks.
PHP's rename() function is used to rename or move a file or directory.
Syntax of rename()
<code>rename(string $oldname, string $newname, resource $context = null): bool</code>Parameter description
$oldname : Path of the existing file or directory.
$newname : Desired new path for the file or directory.
$context (optional): Context resource for additional options.
Return value
Returns true on success, false on failure.
Usage example
<code>$oldname = '/path/to/old/file.txt';
$newname = '/path/to/new/file.txt';
if (rename($oldname, $newname)) {
echo "File renamed successfully!";
} else {
echo "File rename failed!";
}</code>Precautions
If the $newname path already exists, rename() will overwrite it.
The function can rename or move both files and directories.
Renaming across different file systems may fail.
It is recommended to verify that the source file or directory exists and that the script has sufficient permissions before calling rename() .
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.