Are there any security considerations to keep in mind when deleting files from a server using PHP?

When deleting files from a server using PHP, it is important to validate user input to prevent unauthorized access to sensitive files. Additionally, ensure that the file path is properly sanitized to prevent directory traversal attacks. It is also recommended to check file permissions to ensure that the script has the necessary permissions to delete the file.

<?php
$fileToDelete = $_POST['file']; // Assuming file path is passed via POST request

// Validate user input to prevent unauthorized access
if (strpos($fileToDelete, '/path/to/allowed/directory/') !== 0) {
    die('Access denied');
}

// Sanitize file path to prevent directory traversal attacks
$filePath = realpath($fileToDelete);
if (strpos($filePath, '/path/to/allowed/directory/') !== 0) {
    die('Invalid file path');
}

// Check file permissions before deleting
if (is_writable($filePath)) {
    unlink($filePath);
    echo 'File deleted successfully';
} else {
    echo 'Unable to delete file. Check file permissions';
}
?>