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 Courses
php Courses
php Courses
PHP rename() Function: Syntax, Parameters, Return Values, Usage Example, and Precautions

PHP's rename() function is used to rename or move a file or directory.

Syntax of rename()

rename(string $oldname, string $newname, resource $context = null): bool

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

$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!";
}

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().

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPphp-functionrenamefile-system
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.