How to rename a file in PHP?

In PHP, you can rename a file using the rename() function. The rename() function allows you to change the name or location of a file.

Here is an example of how to rename a file in PHP:

$oldFileName = "oldfile.txt"; $newFileName = "newfile.txt"; // Check if file exists if (file_exists($oldFileName)) { // Rename the file if (rename($oldFileName, $newFileName)) { echo "File renamed successfully."; } else { echo "Error renaming file."; } } else { echo "File does not exist."; }

In this example, we first define the original file name ($oldFileName) and the new file name ($newFileName). The file_exists() function is used to check if the original file exists before attempting to rename it. The rename() function is then called to change the name of the file. It returns true if the renaming is successful, and false otherwise. Finally, we provide a message to indicate whether the file was renamed successfully or not.

Make sure to provide the appropriate file paths along with the file names if the file is located in a different directory.