I'm a php amateur, but have always been able to find the code online to achieve my goals. This one has me scratching my head.
I need to delete all images from a directory if their name does not contain the sysid field of a mysql database. (absence of the matching database field means the record has been deleted)
I need a script (that I will execute weekly) to retrieve images from a file, match them by a portion of filename to the corresponding database column, and delete the images without a matching record. I cannot alter the structure of my database to attach image urls, as my data comes from a rets provider and would interrupt the csv import. Here is the scenario. I have daily downloads from the data provider in the form of images stored in a directory named "images", and a csv file which autmatically updates my mysql database table. The images are matched by a very simple pattern where there may be 20 images per record, but they match a field in the table named "sysid" so the name and path of the images would be images/sysid-1.jpg, images/sysid-2.jpg, images/sysid-3.jpg .jpg and so on Where sysid is a six digit number such as 329456. I perform via automated script, a complete truncate and replace of the table data nightly. The problem is the images keep accumulating. They increase by thousands daily. And other than completely deleting the image directory and replacing every month, I cannot find a script to keep the directory size managed. The problem is that there are over 100,000 images in the folder and it is a very large upload.
To summarize:
I need to delete all images from a directory if their name does not contain the sysid field of a mysql database. (absence of the matching database field means the record has been deleted)
Thanks in advance for any help provided. This one seemed easy at first, but now with sleep deprevation, It seems impossible.
I know this should work but it's not efficient enough and I'm hitting my php memory limit I suspect
Code: Select all
<?php
include('../retsconnect.inc.php');
$files = glob('../retsApp/images/*-*.jpeg');
foreach ($files as $image) {
preg_match("/[0-9]{7}|[0-9]{6}/", "$image", $matches);
$sysid = $matches[0];
$query = "SELECT sysid FROM rets WHERE sysid LIKE '$sysid'";
$result = mysql_query($query);
if (empty($result)) {
/*echo '<img class="thumb" alt="img" src="' . $image . '" height="75" width="100" />';*/
echo $image;
}
}
/* unlink("$images");*/
?>
Same Problem. It should work but consumes too much memory. Please help with any suggestions.
Code: Select all
$query = "SELECT sysid FROM rets ";
$result = mysql_query($query);
if ($result) {
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$sysids[] = $row[sysid];
var_dump ($sysids);
}
}
$files = glob('../retsApp/images/*-*.jpeg');
foreach ($files as $image) {
preg_match("/[0-9]{7}|[0-9]{6}/", "$image", $matches);
$string = $matches[0];
if (!in_array($string,$sysids)){
echo $image;
}
}