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

Asked

Viewed 51 times

1

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

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

I need to remove the last row of all files in this directory. I found this code but I couldn’t 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 in 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);
}

?>

1 answer

3


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

?>
  • +1 - When possible, mark as accepted (after system deadline).

  • Just a suggestion, it would be better to write in a separate file (or with another extension) because if running accidentally 2x will take 2 lines. Whenever doing this kind of work, avoid modifying on the original

Browser other questions tagged

You are not signed in. Login or sign up in order to post.