What potential errors can occur when using the rename() function in PHP?
When using the rename() function in PHP, potential errors can occur if the source file does not exist, the destination file already exists, or if the script does not have the necessary permissions to rename the file. To avoid these errors, you can check if the source file exists before attempting to rename it, and also verify that the destination file does not already exist.
$sourceFile = 'source.txt';
$destinationFile = 'destination.txt';
if (file_exists($sourceFile) && !file_exists($destinationFile)) {
if (rename($sourceFile, $destinationFile)) {
echo 'File renamed successfully.';
} else {
echo 'Error renaming file.';
}
} else {
echo 'Source file does not exist or destination file already exists.';
}