Bamuel Bamuel - 7 months ago 30
PHP Question

How to make fwrite() write in the middle of the text file

$username = $_GET['username'];
$steps = $_GET['id'];
$myfile = fopen("save/" . $username . ".txt", "w") or die("Unable to open file!");
fwrite($myfile, $steps);
fclose($myfile);
echo $steps;


This is my code, The issue is that it is replacing the whole .txt file with just $steps while
Test1|b7f2b0b64a3c60a367b40b579b06452d|Male|0|a|02/05/2016|1
is in the text file which therefore it ends up being just
32
if $steps = 32;
in the text file, I want to replace the
0
with
$steps = $_GET['id'];


hint I know its something like this

explode('|',$....)

Answer

It's because you are replacing the file's contents entirely, with $steps, which only contains the $_GET['id'].

Your explode idea can work towards this end, if you are sure that the steps will always be in the same place. Then it'd go somewhat like this.

$username = $_GET['username'];
$steps = $_GET['id'];
$myfile = fopen("save/" . $username . ".txt", "w") or die("Unable to open file!");
//explode on the |
$userData = explode('|', stream_get_contents($myfile)); 
//This should be the steps data. Replace it with the new value
$userData[3] = $steps;
//put the exploded string back together with the new steps value
fwrite($myfile, implode("|", $userData));
fclose($myfile);

fopen and fclose are quite intense operations for such small files, though. A possibly faster way (and easier, too!) is to do it like this:

$username = $_GET['username'];
$steps = $_GET['id'];
$myfile = file_get_contents("save/$username.txt");
//explode on the |
$userData = explode('|', $myfile); 
//This should be the steps data. Replace it with the new value
$userData[3] = $steps;
//put the exploded string back together with the new steps value
file_put_contents("save/$username.txt", implode("|", $userData));

p.s. you can use $variables within the double " strings.

Comments