Home > other >  Delete Array Of Filenames Inside A Foreach Loop Using PHP
Delete Array Of Filenames Inside A Foreach Loop Using PHP

Time:09-22

I am creating a 'delete account' function for users of a site if they want to delete all of their details.

Deleting the relevant records from the database has been pretty straight forward. However, I want to deleted the images they have saved in the site's images folder.

Below is the code I'm trying, a part of which is based on @kmoser's suggestion.

// $db_image_id, $db_image_ext, $db_image_filename are fetched in a previous code block for when images are outputted on the page.

if(isset($_POST['delete-account'])) {

    $loggedInUser = $_SESSION['logged_in'];
    $imagesLibrary = 'images-lib/';
    $imagesDownload = 'images-download/';

    try {

    $s = $connection->prepare("SELECT filename FROM `imageposts` WHERE user_id = :user_id");
    $s->bindParam(':user_id', $loggedInUser);
    $s->execute();

    // -- DELETE THE USER'S IMAGE FILES FROM 'IMAGES-LIB' FOLDER
    while ($row = $s->fetch()) { 
        if (isset($pattern)) {
            $pattern = $imagesLibrary . $row['filename'] . '-{500,750,1000,1500}' . '.' . $row['file_extension'];
            foreach (glob($pattern, GLOB_BRACE) as $filenames) {
                unlink($filenames);
            }
        }
    }
                        
    header("Location: index.php");

    } catch (PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
}

The key piece of the above code is this snippet below:

// -- DELETE IMAGE FILES FROM 'IMAGES-LIB' FOLDER
while ($row = $s->fetch()) { 
    if (isset($pattern)) {
        $pattern = $imagesLibrary . $row['filename'] . '-{500,750,1000,1500}' . '.' . $row['file_extension'];
        foreach (glob($pattern, GLOB_BRACE) as $filenames) {
            unlink($filenames);
        }
    }
}

I was initially getting an error PHP Notice: Undefined index: file_extension in /Applications/MAMP/htdocs/site/profile-edit.php in relation to the 3rd line of PHP code above that declares the $pattern variable. I've managed to fix this by wrapping the code in the if(isset($pattern)) if statement that is now present. I don't get any error logs now, but the files are not being deleted out of the 'images-lib' directory.

A typical filename example is 6146972e2dc73_1632016174-500.jpeg

Here is an example of how the files look in the database:

image file names in MySQL database

When outputted onto a page in an <img> tag, the size e.g. -500 part of the filename is concatenated on with a string inside the src attribute.

src="<?php echo '/images-lib/' . $db_image_filename . '-500' . '.' . $db_image_ext; ?>"

Any help or assistance on how to delete images specific to a user from the images directory would be wonderful.

CodePudding user response:

There's no need to store the filenames and extensions in separate arrays, or even in an array at all. Just fetch every image filename and extension in a loop, assemble it into a pattern (e.g. images/6146972e2dc73_1632016174-{500,750,1000,1500}.jpeg, then glob() the pattern to find each matching file and unlink it:

while ($row = $s->fetch()) { 
    $pattern = $imagesLibrary . $row['filename'] . '-{500,750,1000,1500}.' . $row['file_extension'];
    foreach (glob($pattern, GLOB_BRACE) as $filename) {
        unlink($filename);
    }
}
  • Related