如何在php中删除下一个文件


How to delete the next file in php

假设我有一个文件夹包含99tf.txt, 40.txt, 65.txt,按任意顺序

如果当前的脚本var是40.txt:我希望它删除65.txt(或下一个文件)

I was looking into something like that:

$file='40.txt';

if ($handle = opendir('./log/')) {
    $entry= readdir($handle);
  //move pointer to 40.txt
    while ($file != $entry && $entry !== false) {
      $entry = readdir($handle)
    }
   //go to the next file
   $entry = readdir($handle)
  if(is_file('./log/'.$entry)){
    unlink('./log/'.$entry);
    }
}

但是我希望避免每次都进入循环,因为文件夹中可能有很多文件。所以有没有办法改变$句柄指针到'$file'直接并删除下一个文件?

如果您不介意使用scandir,那么这应该更适合您。

$file = '40.txt';
$contents = scandir('./log/');
// Should already be sorted, but do again for safe measure
sort($contents);
// Make sure the file is in there.
if (false !== $index = array_search($file, $contents)) {
    // If the file is at the end, do nothing.
    if ($index !== count($contents)) {
        // Remove the next index
        unlink('./log/' . $contents[$index + 1]);
    }
}

关于顺序不重要,你不需要排序。然而,值得注意的是,您的方法需要更长的时间,但使用更少的内存,而此方法相反,更快,但可能更多的内存消耗。

<?php 
    $file = '40.txt';
    $scan_folder = scandir('./log/');
    $num_files = count($scan_folder);
    if ($num_files > 1) {
    $file_key = array_search($file, $scan_folder) +1;
    unlink('./log/'.$file_key);
    } else {
    // here you will preserve only 1 file all others can be removed every time this script is executed
    }
?>