Remove images that are not present in the database

Asked

Viewed 89 times

3

I started working on a site already made by a former programmer who has a page inserting and removing images. However, when it removes, 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.

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

  • 1

    creates a folder for images that are still being used, in the loop of the search you copy the image to this new folder, you will have a folder with all images and another with only the ones that are in use

  • I will try this, I will make a backup because there are more than 2000 photos

  • this, makes a security backup

1 answer

2


I had the same problem as you. I have a code made by me ready in PDO and Mysql, I will leave here for your logical basis. I will try to explain as much as possible. (I will not include lines of code such as database connection and so on because I find it unnecessary).


> First

My photos were saved by an automatically generated code, which was in my database in a field called code. I mean, in the database I had the code (ex: 123456) and in the folder I had the image saved with the extension code (ex: 123456.png).

Also, I renamed my original folder with the photos to "pasture" and created a folder called "pastaNova", where will be the images that are yes present in my database.


> According to

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


> Get to work

<?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 take a backup before! Photos are always important. Even after doing all this, I haven’t deleted my backup file because you never know when it will need!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.