I've got a piece of PHP code that's supposed to find an appropriate line in a txt file and replace it with a new value. Everything works as long as the length of a string doesn't change. If it's one character longer, the following line gets one character deleted and so on. I have no clue how to fix it. Also I didn't include the part that searches for the right line, it works alright and I don't think it's relevant.
PHP code:
$f = fopen("score.txt", "r+") or die("error");
$s = $_SESSION["id"].";".$_POST['S']."\n";
(...)
fwrite($f,$s);
fclose($f);
TXT file before:
N01;99
N02;102
N03;11
TXT file after changing the value for N01 to 100 (one character longer):
N01;100
02;102
N03;11
When you write to a file, you're just overwriting bytes. There's no way to insert and delete directly into a file.
What you need to do is read the whole file into memory, replace what you want, then write it all back to the file.
You can use the file()
function to read the file into an array, where each element is one line of the file.
$lines = file("score.txt");
foreach ($lines as &$line) {
list ($id, $s) = explode(';', $line);
if ($id == $_SESSION['id']) {
$line = $_SESSION["id"].";".$_POST['S']."\n";
break;
}
}
file_put_contents("score.txt", implode('', $lines));