w3resource

PHP script to rename a file


6. Rename a File

Write a PHP script to rename a file.

Sample Solution:

PHP Code :

<?php
$oldFilename = "i:/example.txt";
$newFilename = "i:/new_example.txt";

try {
    if (file_exists($oldFilename)) {
        if (rename($oldFilename, $newFilename)) {
            echo "File renamed successfully.";
        } else {
            throw new Exception("Error renaming the file.");
        }
    } else {
        throw new Exception("File does not exist.");
    }
} catch (Exception $e) {
    echo "An error occurred: " . $e->getMessage();
}
?>

Sample Output:

File renamed successfully.

Explanation:

In the above exercise -

  • We have two variables: $oldFilename holds the current name of the file you want to rename, and $newFilename holds the desired new name of the file.
  • Inside the try block, we first check if the old file exists using file_exists(). If it exists, we use the rename() function to rename the file. If the renaming operation is successful, we display a success message. If the renaming fails, we throw an exception with the error message "Error renaming the file."
  • If the old file does not exist, we throw an exception with the error message "File does not exist."
  • In the catch block, we catch the exception and display an error message using $e->getMessage().

Flowchart:

Flowchart: PHP script to rename a file

For more Practice: Solve these Related Problems:

  • Write a PHP script that renames multiple files in a directory by appending a timestamp to their existing names.
  • Write a PHP function to check if a file exists before renaming it, and return an error message if it does not.
  • Write a PHP program to rename files based on their file extensions (e.g., change .txt files to .bak).
  • Write a PHP script to rename a file only if the new name does not conflict with existing filenames in the directory.

Go to:


PREV : CSV File to Table.
NEXT : Copy a File.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.