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);
}
?>
List all files in the directory and making that change that works on a loop wouldn’t work?
– Diego Rafael Souza