PHP rename() | Rename a File or Directory

The PHP rename() function is used when we need to change the name of a file or a directory. For example:

<?php
   $chk = rename("myfile.txt", "yourfile.txt");
   if($chk)
      echo "<p>Name changed successfully!</p>";
   else
      echo "<p>Unable to change the name.</p>";
?>

The output of the above PHP example using the rename() function is shown in the snapshot given below:

php rename function

That is, after executing the above PHP code, the name of the file myfile.txt gets changed to yourfile.txt.

PHP rename() Syntax

The syntax of the rename() function in PHP is:

rename(oldName, newName, context)

The first two (oldName and newName) parameters are required, whereas the last parameter is optional and is used to specify the context resource while renaming a file or a directory.

PHP rename() function example

Consider the following PHP code as another example of the rename() function:

PHP Code
<?php
   $old_file_name = "old_file.txt";
   $new_file_name = "new_file.txt";

   if (file_exists($old_file_name)) {
      if (rename($old_file_name, $new_file_name)) {
         echo "File renamed successfully.";
      } else {
         echo "File renaming failed.";
      }
   } else {
      echo "File does not exist.";
   }
?>
Output
File renamed successfully.

And if the file "old_file.txt" does not exist in the current directory, then you will get the following output:

File does not exist.

Advantages of the rename() function in PHP

Disadvantages of the rename() function in PHP

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!