Are there any best practices to follow when using chmod in PHP to avoid permission denied errors?

When using chmod in PHP, it's important to ensure that the script has the necessary permissions to modify the file permissions. To avoid permission denied errors, it's best practice to check if the file exists and if the script has the appropriate permissions before attempting to change the file permissions.

$file = 'example.txt';

if (file_exists($file)) {
    if (is_writable($file)) {
        chmod($file, 0644);
        echo "File permissions changed successfully.";
    } else {
        echo "Permission denied. Script does not have write access to the file.";
    }
} else {
    echo "File does not exist.";
}