Delete orphaned files

0

I have a content management system that I use on my car shop site, it has 3 tables that are dependent, Shop, Cars, and Cars.

When registering a store, I add a car and several photos of that car, all in their corresponding tables, but I noticed that the system was not excluding cascading records, they were getting very orphaned files, that is, when I deleted the store, was to delete all the cars from that store and all the photos of the cars, so I got a lot of lost space on the server, so I need to delete these photos.

I searched in some forums and found nothing complete, just fragments of what I wanted, so I was putting things together and I would like your opinion where I can improve or if I am doing wrong, follow the code:

try{
//Caminho para pasta
$path = "upload/imagens/carros/";
$diretorio = dir($path);

//Faço uma leitura em toda pasta e adiciono cada arquivo no array
$arquivos = array();
while ($file = $diretorio->read()) {
    if ($file != "." && $file != "..") {
        array_push($arquivos, $file);
    }
}

//Conexão com BD
$conn = new PDO('mysql:host=localhost;dbname=minhaloja', 'user', 'senha');

//Seleciono todos os registros 
$stmt = $conn->prepare('SELECT 'imagem' FROM 'carrosfotos'');
$stmt->execute(array());
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

//Percorro o array e comparo com o BD se o arquivo encontrado está cadastrado
foreach ($arquivos as $foto){
        if (in_array($foto, array_column($result, 'imagem'))) {
        echo '<pre>';
        echo 'A imagem'.$foto.' está cadastrada.';
        echo '</pre>';
        } else {
            unlink($path . $foto);
        }

}
} catch (PDOException $e) {
    echo 'ERRO: ' . $e->getMessage();
    $diretorio->close();
}

Thank you.

    
asked by anonymous 23.05.2018 / 05:52

0 answers