How to rename a file in PHP?

By IncludeHelp Last updated : January 10, 2024

Problem statement

Write a PHP program to rename a file.

Renaming a file

To rename a file in PHP, use the rename() function. First, check the existence of the file, if it exists then use the rename() method by passing the current (old file name) and new file name.

Note

The rename() function can also be used to rename a directory.

PHP program to rename a file

In the program, we will rename the file1.txt name with a new name file2.txt.

<?php
// file names
$old_file = "file1.txt";
$new_file = "file2.txt";

try {
    // check if file exists or not
    if (file_exists($old_file)) {
        // rename it
        if (rename($old_file, $new_file)) {
            echo "Success. File renamed.";
        } else {
            throw new Exception("Failed. Error in renaming the file.");
        }
    } else {
        throw new Exception("Failed. File does not exist.");
    }
} catch (Exception $e) {
    echo "Error occurred: " . $e->getMessage();
}
?>

Output

The output of the above program is:

Success. File renamed.

To understand the above program, you should have the basic knowledge of the following PHP topics:

More PHP File Handling Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.