How can a custom logging system help in identifying the cause of unexpected file deletions in a PHP script?

A custom logging system can help in identifying the cause of unexpected file deletions in a PHP script by logging relevant information such as the file path, timestamp, and any related error messages. This allows developers to track the sequence of events leading up to the deletion and pinpoint any potential issues in the code or environment that may have caused it.

// Custom logging function to log file deletions
function logFileDeletion($filePath, $errorMessage) {
    $logMessage = "File deleted: " . $filePath . " | Error: " . $errorMessage . " | Timestamp: " . date('Y-m-d H:i:s') . PHP_EOL;
    
    // Append log message to a log file
    file_put_contents('file_deletion_log.txt', $logMessage, FILE_APPEND);
}

// Example usage
$filePath = 'example.txt';

if (unlink($filePath)) {
    echo "File deleted successfully";
} else {
    $errorMessage = error_get_last()['message'];
    logFileDeletion($filePath, $errorMessage);
    echo "Failed to delete file";
}