How can PHP developers ensure that the unlink() function is used securely to prevent unauthorized file deletions?

To ensure that the unlink() function is used securely to prevent unauthorized file deletions, PHP developers should validate user input and check permissions before deleting files. This can be done by verifying that the file to be deleted exists and that the user has the necessary permissions to delete it.

$file = 'example.txt';

if (file_exists($file) && is_writable($file)) {
    unlink($file);
    echo "File deleted successfully.";
} else {
    echo "Unable to delete file.";
}