我想删除特定类别中超过特定年龄(例如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),无法在服务器上列出。
答案 0 :(得分:2)
好的,所以你只保存数据库中的图像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);
}
}
答案 1 :(得分:0)
我为我的问题编写了这个脚本,如果有更多的改进,那就完美地运行,然后告诉我
<?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);
?>