php – Remove images that are not present in the database

Question:

I started working on a website already made by a former programmer that has an image insertion and removal page. However, when it removes it, it only takes it out of the database leaving the image there, that is, it takes up space. It's been 2 years since the creation of that page and many images have been deleted.

Can I loop through each data in the database and then compare files that don't exist in the folder?

Answer:

I had the same problem as you. I have a code made by me ready in PDO and Mysql, I'll leave it here for your logic base. I will try to explain as much as possible. (I won't include lines of code like database connection etc, as I think it's unnecessary).


> First

My photos were saved by an automatically generated code, which was in my database in a field called code . In other words, 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 "old folder" and created a folder called "new folder " , where the images that are actually present in my database will be.


> second

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


> Let's go

<?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 you!

@edit: remember to make a backup first! Photos are always important. Even after all that was done, I didn't delete my backup file, because you never know when you'll need it!

Scroll to Top