Skip to content
PHP Logo

When designing a PHP script to delete files based on user interaction, what considerations should be made regarding the structure of the code, separation of concerns, and error handling mechanisms?

When designing a PHP script to delete files based on user interaction, it is important to separate concerns by keeping the code modular and organized. This can be achieved by creating separate functions for handling user input, file deletion, and error handling. Additionally, error handling mechanisms should be implemented to gracefully handle any potential issues that may arise during the file deletion process.

php
<?php

// Function to handle user input and initiate file deletion
function deleteFile($filename) {
    if (file_exists($filename)) {
        if (unlink($filename)) {
            echo "File deleted successfully.";
        } else {
            echo "Error deleting file.";
        }
    } else {
        echo "File does not exist.";
    }
}

// Get user input
$filename = $_POST['filename'];

// Call the deleteFile function
deleteFile($filename);

?>