【问题标题】:How to Delete few older images using php?如何使用 php 删除一些旧图像?
【发布时间】:2015-10-05 12:00:06
【问题描述】:

我想删除特定类别中超过特定​​年龄(例如 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 msn_story_images
------------------------------------
ID    image(url)   thumbnail   sortstyID

images 文件夹非常大(大约 19GB),无法在服务器上列出。

【问题讨论】:

  • 您使用什么类型的数据库以及如何访问它?

标签: php mysql unlink filemtime


【解决方案1】:

好的,所以您只将图像 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);
  }
}

【讨论】:

  • 我可以在线申请任何风险因素吗?
  • 当然可以。为了消除重大风险,请始终在本地或开发环境中测试您的代码。此外,在应用删除作业时,请确保将要删除的系统用户只有目标文件夹的写入权限,而不是父文件夹。
  • 您的代码运行良好,我展示了成功运行的脚本
【解决方案2】:

我为我的问题制作了这个脚本,如果有更多改进,那么它可以完美运行,然后告诉我

   <?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);


?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 2011-02-22
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多