Backend Development 2 min read

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

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

BackendPHPphp-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

login 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.