255 of 410 menu

The rename Function

The rename function renames a file or directory. The first parameter of the function is the current filename or path to it, the second parameter is the new name or path. The function returns true on success and false on error.

Syntax

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

Example

Rename the file from 'old.txt' to 'new.txt':

<?php $res = rename('old.txt', 'new.txt'); var_dump($res); ?>

Code execution result:

true

Example

Move the file to another directory:

<?php $res = rename('file.txt', 'newdir/file.txt'); var_dump($res); ?>

Code execution result:

true

Example

Let's try to rename a non-existent file:

<?php $res = rename('nonexistent.txt', 'new.txt'); var_dump($res); ?>

Code execution result:

false

Example

Rename a directory:

<?php $res = rename('olddir', 'newdir'); var_dump($res); ?>

Code execution result:

true

See Also

  • the copy function,
    which copies a file
  • the unlink function,
    which deletes a file
  • the move_uploaded_file function,
    which moves an uploaded file
byenru