This is a tough one to explain in php. I've got a system that read a file, breaks the data by lines (" ") and then looks through the lines and comes up with a new data without one line marked by a $n variable. Then it writes.
Here's the problem: Its like fwrite is going first (when its last), then fread (which is first), then fwrite (which is last).
If I have a file with 31 lines, the fread will read the file as if it has 30 lines already with the proper line taken out. Then it will take out the proper line again, so I'll end up with a 29 line file. BUT if I remove the fread, the 31 line file loads properly. If I don't have a line removed, then it will keep all 31 lines.
I've simplified the code as much as I could. I've even added sleep(10) to hopefully delay fwrite until fread has read.
When I output a different file that works just fine as its supposed to, but if I try to take that output file and rename it to the original file, I still get the same problem. I've also used file_get_contents with file_put_contents with the same results.
Thanks for any help. Maybe you guys can tell me where I'm going wrong. Here's the code:
$handle = fopen($filename, 'r');
$Data = fread($handle, filesize($filename));
fclose($handle);
$pieces = explode("
", $Data);
// $n = the line to delete
$info = '';
for($i = 0 ; $i < sizeof($pieces) ; $i++){
if($_REQUEST['n'] == $i && $pieces[$i] != ''){
$info .= $pieces[$i]."
";
}
}
// $filename never changes
// $info is $Data without the specific $n line
$fp = fopen($filename, 'w+');
fwrite($fp, $info);
fclose($fp);