0

I like to remove images that are not used from the server

The code i write is working but is very slow take more than 30 min. is there any fatser way to do it ?

Files: around 150k

DB records: around 120k

Query executed time: 1 sec.

$sql = "SELECT image, media FROM products p, product_media pm WHERE p.id = pm.id";
$result = mysqli_query($con, $sql) or die(mysql_error());
$row = mysqli_fetch_all ($result, MYSQLI_ASSOC);

$directory = "images/products/full";
$images = glob("$directory/*.{jpg,jpeg,png,bmp}", GLOB_BRACE);

foreach($images as $key => $image) {
  $path = $image;
  $image = str_replace('images/products/full/', '', $image);

  if (!in_array($image, $row)) {
    unlink($path);
  }

}
bobi
  • 169
  • 2
  • 16
  • how fast is the SQL query itself and is it faster when the two tables are joined? 1/2hr seems very slow - are there a huge number of files / records involved? – Professor Abronsius Jun 07 '22 at 06:36
  • @ProfessorAbronsius files are around 150k, query time is 1 sec. with around 120k records – bobi Jun 07 '22 at 06:46
  • 1
    Surely though this is a one-time operation? Once you have deleted all images that are not listed in your database then there should be no need for this to be done again ? – Professor Abronsius Jun 07 '22 at 06:54
  • Get pictures filenames list. Load this list from file to temptable. Select the rows which are absent in your working table. Save these rows to another file. Delete pictures listed in this file. – Akina Jun 07 '22 at 07:06
  • 2
    FYI as an aside, `or die(mysql_error())` won't do anything useful because it relates to mysql_ not mysqli_. But you can improve your error handling from this naive "die" approach anyway - see [mysqli or die, does it have to die?](https://stackoverflow.com/questions/15318368/mysqli-or-die-does-it-have-to-die) to understand a better and easier way. – ADyson Jun 07 '22 at 09:11
  • How many images are unlinked? Is it all of the 120K? How long does the glob take? How long does the foreach loop take? – Rick James Jun 20 '22 at 05:05

0 Answers0