PHP Function Reference

PHP rename() Function



The PHP rename() function attempts to rename a file or directory, moving it between directories if necessary. If renaming a file and newname exists, it will be overwritten. If renaming a directory and newname exists, this function will raise a warning.

Syntax

rename(oldname, newname, context)

Parameters

oldname Required. Specify the file or directory to be renamed.
newname Required. Specify the new name for the file or directory.
context Optional. Specify the context of the file handle. Context is a set of options that can modify the behavior of a stream.

Return Value

Returns true on success or false on failure.

Example:

Lets assume that we have a file called test.txt in the current working directory. The example below demonstrates on using this function to rename this file.

<?php
$oldname = 'test.txt';
$newname = 'demo.txt';

//renaming the file
$success = rename($oldname, $newname);

if($success) {
  echo "$oldname is renamed to $newname.\n";
} else {
  echo "$oldname can not be renamed to $newname.\n";
}
?>

The output of the above code will be:

test.txt is renamed to demo.txt.

Example:

Consider one more example where this function is used to rename a directory.

<?php
//creating a folder in the current directory
mkdir("temp1");

$oldname = 'temp1';
$newname = 'temp2';

//renaming the directory
$success = rename($oldname, $newname);

if($success) {
  echo "$oldname is renamed to $newname.\n";
} else {
  echo "$oldname can not be renamed to $newname.\n";
}
?>

The output of the above code will be:

temp1 is renamed to temp2.

❮ PHP Filesystem Reference