如何使用 php 删除一些旧图像?

How to Delete few older images using php?

我想从特定类别中删除超过特定年龄(比如 2 个月)的图像。

如果我使用以下代码,这些图像位于某个目录中:

<?php

// define the directory
$dir = "images/";

// cycle through all files in the directory
foreach (glob($dir."*") as $file) {

    // if file is 2 Month (5.184e+6 seconds) old then delete it
    if (filemtime($file) < time() - 5.184e+6) {
        unlink($file);
    }
}

?>

然后它会删除所有 2 个月前的图像,但我想按类别删除图像。

这是我数据库中的 table:

------------------------------------
table msn_story_images
------------------------------------
ID    image(url)   thumbnail   sortstyID

图片文件夹很大(大约 19GB),无法在服务器上列出。

好的,所以您只在数据库中保存图像 URL。我想您可以通过图像名称在数据库图像和文件系统图像之间建立逻辑关系。我建议首先从数据库中获取相关图像,然后将它们放入仅包含 URL 的平面数组中。遍历数组并转换图像名称以省略前导 URL 部分。一个简化的例子:

foreach($imagesWithUrl as $idx => $image) {
  $imagesWithUrl[$idx] = basename($image);
}

然后,在您的循环中,检查此图像是否存在于来自 DB 的数组中:

/*** cycle through all files in the directory ***/
foreach (glob($dir."*") as $file) {

  /*** if file is 2 Month (5.184e+6 seconds) old then delete it ***/
  if (filemtime($file) < time() - 5.184e+6 && in_array(basename($file), $imagesWithUrl)) {
      unlink($file);
  }
}

我为我的问题制作了这个脚本,运行 完美,如果有更多改进,请告诉我

   <?php
$conn = new mysqli('localhost', 'freemed_mainuser', 'xDPf$$!O!H61','freemed_main');


$sql="select img.styid imgid,concat('sam_data/story/images/',img.image) as img,story.id storyid,story.title storytitle,story.insdatetime insdatetime from msn_story_images img , msn_stories story WHERE  img.styid=story.id and insdatetime < DATE_SUB( CURDATE( ) , INTERVAL 60 
DAY ) 
AND catid NOT 
IN ( 1, 86, 85, 88, 87 )
";
$data = mysqli_query($conn,$sql);


while($row=mysqli_fetch_array($data)){

    unlink($row['img']);

    echo "files deleted";



}

/*and delete matching rows from DB*/ 
$del="DELETE msn_story_images,
msn_stories FROM msn_stories INNER JOIN msn_story_images WHERE msn_story_images.styid = msn_stories.id AND msn_stories.insdatetime < DATE_SUB( CURDATE( ) , INTERVAL 60 DAY ) AND msn_stories.catid NOT IN ( 1, 86, 85, 88, 87 )";
$del_data=mysqli_query($conn,$del);


?>