replacing a single line of a .txt file using php

I am trying to use a php call through AJAX to replace a single line of a .txt file, in which I store user-specific information. The problem is that if I use fwrite once getting to the correct line, it leaves any previous information which is longer than the replacement information untouched at the end. Is there an easy …

via PHP Website Development » Search Results » ajax:

replacing a single line of a .txt file using php

I am trying to use a php call through AJAX to replace a single line of a .txt file, in which I store user-specific information. The problem is that if I use fwrite once getting to the correct line, it leaves any previous information which is longer than the replacement information untouched at the end. Is there an easy way to clear a single line in a .txt file with php that I can call first? Example of what is happening – let’s say I’m storing favorite composer, and a user has “Beethoven” in their .txt file, and want’s to change it to “Mozart”, when I used fwrite over “Beethoven” with “Mozart”, I am getting “Mozartven” as the new line. I am using “r+” in the fopen call, as I only want to replace a single line at a time.
………………………………….

If this configuration data doesn’t need to be made available to non-PHP apps, consider using var_export() instead. It’s basically var_dump/print_r, but outputs the variable as parseable PHP code. This’d reduce your code to:
include(‘config.php’);
$CONFIG[‘musician’] = ‘Mozart’;
file_put_contents(‘config.php’, ‘………………………………….

This is a code I’ve wrote some time ago to delete line from the file, it have to be modified. Also, it will work correctly if the new line is shorter than the old one, for longer lines heavy modification will be required.
The key is the second while loop, in which all contents of the file after the change is being rewritten in the correct position in the file.
$size = filesize(‘test.txt’);
$file = fopen(‘test.txt’, ‘r+’);
$lineToDelete = 3;
$counter = 1;

while ($counter < $lineToDelete)
fgets($file); // skip
$counter++;

$position = ftell($file);
$lineToRemove = fgets($file);
$bufferSize = strlen($lineToRemove);
while ($newLine = fread($file, $bufferSize))
fseek($file, $position, SEEK_SET);
fwrite($file, $newLine);
$position = ftell($file);
fseek($file, $bufferSize, SEEK_CUR);

ftruncate($file, $size – $bufferSize);
echo ‘Done’;
fclose($file);
?>

For more info: replacing a single line of a .txt file using php

PHP Website Development » Search Results » ajax

replacing a single line of a .txt file using php

Share this post:

Related Posts

Leave a Comment