delete image from folder PHP

delete image from folder PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Securely Deleting Images from a Folder in PHP

Your current implementation uses glob("img/*") to retrieve filenames and renders an HTML list with delete buttons. While this approach works for displaying files, it lacks the necessary mechanism to associate a specific file with a delete action. To remove an image when the user clicks the button, you must transmit the filename from the browser back to the server and execute a secure deletion routine.

The first step is moving away from static HTML forms that simply say "Delete image." Instead, you need to generate a form for each image entry that submits the specific file path to a dedicated handler. In your loop where you display the images, wrap the image tag inside a <form> element. This form should use the POST method and target a specific action URL or route.

Here is how you can structure the HTML generation within your PHP loop:

foreach ($files as $file) {
    // Ensure we only process actual files, not directories
    if (is_file($file)) {
        $filename = basename($file);
        
        echo "<div class='divimages'>"; 
        echo "<img src='" . htmlspecialchars($file) . "' alt='Image'>";
        
        // Create a form that submits the filename to a delete handler
        echo "<form action='/delete-image' method='POST' style='display:inline;'>";
        echo "<input type='hidden' name='filename' value='" . htmlspecialchars($filename) . "'>";
        echo "<input type='submit' value='Delete image'>";
        echo "</form>";
        
        echo "</div>";  
    }
}

In this example, we use htmlspecialchars() to prevent XSS vulnerabilities when outputting file paths. We also explicitly check if the item is a file using is_file(), which is crucial because glob returns directory entries as well if they match the pattern. The hidden input field named filename carries the specific data required for the server to know which asset to remove.

Once the form is submitted, you need a route or script that handles the request at /delete-image. This endpoint should retrieve the filename parameter from the POST data and locate the full path of the file on the filesystem.

// delete-image.php or a route handler
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['filename'])) {
    $filename = $_POST['filename'];
    
    // Construct the full path safely
    $fullPath = __DIR__ . '/img/' . basename($filename);
    
    if (file_exists($fullPath)) {
        // Securely delete the file
        if (!unlink($fullPath)) {
            // Handle error appropriately, e.g., log it
            die("Failed to delete file.");
        }
        
        // Optionally update your database here before deletion
    } else {
        die("File not found.");
    }
}

A critical pitfall in this scenario is trusting user input blindly. Although the filename comes from the form you generated, always validate that the file exists and resides within your intended directory (img/). Attackers might attempt to delete files outside your image folder by manipulating the filename parameter if you do not use dirname() or construct the path relative to a known base directory.

Furthermore, consider the database aspect of your application. If your table tracks which images belong to specific records, you should update or delete the corresponding rows in your database before attempting to remove the file from the filesystem. Deleting the physical file without updating the database will leave orphaned entries that may cause broken image links or data integrity issues. Conversely, removing the database record but leaving the file on the disk wastes storage space and creates security risks if those files are accessed directly via URL.

For larger applications using frameworks like Laravel, you would typically leverage the Storage facade to handle these operations, ensuring consistent behavior across environments. However, the fundamental principle remains the same: collect the identifier securely, validate the target location, update related data structures, and then remove the file.

Our network