How can file existence and permissions be checked before using the rename function in PHP?

Before using the rename function in PHP, it is important to check whether the source file exists and has the necessary permissions to be renamed. This can be done using functions like file_exists() and is_readable() to ensure that the file can be accessed and modified. By performing these checks before calling the rename function, you can prevent potential errors or unexpected behavior in your code.

$sourceFile = 'example.txt';
$destinationFile = 'new_example.txt';

if (file_exists($sourceFile) && is_writable($sourceFile)) {
    rename($sourceFile, $destinationFile);
    echo 'File renamed successfully.';
} else {
    echo 'Source file does not exist or is not writable.';
}