Remove images that are not present in the database

3

I started working on a site already made by an old programmer that has a page for insertion and removal of images. However, when it removes, it only takes the database leaving the image there, ie, it takes up space. It's been 2 years since the page was created and many images have been deleted.

Can I loop through each data in the database and then compare the files that do not exist in the folder?

    
asked by anonymous 29.06.2018 / 12:43

1 answer

2

I had the same problem as you. I have a code done by me ready in PDO and Mysql, I'll leave here for your logical basis. I'll try to explain as much as possible. (I will not include lines of code like connection with database and etc, as I think it is unnecessary).

> First

My photos were saved by an auto-generated code that was in my database in a field called code . That is, in the database I had the code (ex: 123456) and in the folder I had the image saved with the code.extension ex: 123456.png) .

In addition, I renamed my original folder with the photos to folder and created a folder called folder > , where the images that are actually present in my database will remain.

> Second

Leaving for programming. I searched all the records in my table in a while and for each of them, I copied the image with the same code from the old folder to the new folder using the copy () of php. I did not worry about security, as I would do this locally and then remove the feature. That is, no one would have access.

> Hands on

<?php
include("./conexao.php");
$sql = $pdo->query("SELECT * FROM fotos");
$sql->execute();
while($imagem = $sql->fetch(PDO::FETCH_ASSOC)){
  $imagemOriginal = "./pastaAntiga/".$imagem['codigo'].".png"; //caminho da imagem na pasta original
  $imagemCopia = "./pastaNova/".$imagem['codigo'].".png"; //caminho onde será salvo
  if (copy($imagemOriginal,$imagemCopia)) { // função copy(copiarDe,copiarPara)
    echo "Imagem de código: ".$imagem['codigo']." copiada com sucesso!"; //mensagem caso a imagem seja copiada
    echo "<br>";
  } else {
    echo "Erro ao copiar imagem de código: ".$imagem['codigo']; // mensagem caso a imagem não seja copiada
  }
}
?>

I hope it helps!

@edit: remember to make a backup before! Photos are always important. Even after doing all this, I did not delete my backup file, because you never know when you will need it!

    
29.06.2018 / 18:55