PHP File Name Change in Folder Example

Sure! To change a file name in a folder using PHP, you can use the rename() function. Here’s an example:

Assuming you have a file named “old_filename.txt” in a folder named “files”, and you want to change it to “new_filename.txt”, you can use the following PHP code:

<?php
$oldFileName = 'files/old_filename.txt';
$newFileName = 'files/new_filename.txt';

// Check if the file exists
if (file_exists($oldFileName)) {
    // Attempt to rename the file
    if (rename($oldFileName, $newFileName)) {
        echo "File name changed successfully.";
    } else {
        echo "Error: Unable to change file name.";
    }
} else {
    echo "Error: File does not exist.";
}
?>

Make sure to provide the correct file paths for $oldFileName and $newFileName based on your folder structure. The file_exists() function is used to check if the old file exists before attempting to rename it. If the rename operation is successful, it will echo “File name changed successfully,” otherwise it will echo an error message.

Ensure that the PHP script has the necessary permissions to perform file operations in the target folder. Always test file renaming with caution, especially if the folder contains critical files.