Remove a specific line in all files in a directory using PHP

1

I have a directory with 5500 files named randomly without extension, for example:

  • 4as6d4ad
  • 4asd564ad
  • 1mi3jh
  • 019i43nmasf

I need to remove the last line of all files in this directory. I found this code but could not adapt it:

<?php 

// load the data and delete the line from the array 
$lines = file('filename.txt'); 
$last = sizeof($lines) - 1 ; 
unset($lines[$last]); 

// write the new data to the file 
$fp = fopen('filename.txt', 'w'); 
fwrite($fp, implode('', $lines)); 
fclose($fp); 

?>

The above code works, but I have to specify file by file.

Edit: With the help of the comments, I was able to solve the problem using:

<?php 
if ($handle = opendir('.')) {

    while (false !== ($entry = readdir($handle))) {

        if ($entry != "." && $entry != "..") {

// load the data and delete the line from the array 
$lines = file($entry); 
$last = sizeof($lines) - 1 ; 
unset($lines[$last]); 

// write the new data to the file 
$fp = fopen($entry, 'w'); 
fwrite($fp, implode('', $lines)); 
fclose($fp); 


        }
    }

    closedir($handle);
}

?>
    
asked by anonymous 07.04.2018 / 15:17

1 answer

2
<?php 
if ($handle = opendir('.')) {

    while (false !== ($entry = readdir($handle))) {

        if ($entry != "." && $entry != "..") {

// load the data and delete the line from the array 
$lines = file($entry); 
$last = sizeof($lines) - 1 ; 
unset($lines[$last]); 

// write the new data to the file 
$fp = fopen($entry, 'w'); 
fwrite($fp, implode('', $lines)); 
fclose($fp); 


        }
    }

    closedir($handle);
}

?>
    
07.04.2018 / 17:28