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

$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('|',$....)

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.

Note that you are using the w file mode, which will truncate the file on opening it. This means you will be losing data if you don't set it aside first. As per the documentation:
Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
Using fgetcsv you could first read the data and then save the entire string back to the file:
$username = $_GET['username'];
$steps = $_GET['id'];
$myfile = fopen("save/" . $username . ".txt", "r+") or die("Unable to open file!");
// Get the current data from the file
$data = fgetcsv($myfile, 0, '|');
// Now replace the 4th column with our steps
$data[3] = $steps;
// Now truncate the file
ftruncate($myfile, 0);
// And save the new data back to the file
fwrite($myfile, implode('|', $data));
fclose($myfile);

Related

php replace an string on exist file .env

my question is similiar like this : Replace string in text file using PHP
but i want replace by spesification variable
for example, i have already file exist .env
variable_1=data_2021
variable_99=data_2050
variable_991=data_2061
so how i can replace by spesificiation name variable for the value ?
i want replace data_2050 with data_2051 without change on other text where the variable is variable_99
$myfile = fopen("../../.env.securepay", "w") or die("Unable to open file!");
fwrite($myfile, 'variable_99='.$value);
fclose($myfile);
// $myfile = fopen("../../.env", "w") or die("Unable to open file!");
// fseek($myfile, 0);
// fwrite($myfile, 'variable_99 ='.$value);
// fclose($myfile);
// $oldMessage = 'variable_99';
// $deletedFormat = '';
// //read the entire string
// $str=file_get_contents('../../.env.securepay');
// //replace something in the file string - this is a VERY simple example
// $str=str_replace($oldMessage, $deletedFormat, $str);
// //write the entire string
// file_put_contents('../../.env', $str);
above code just remove all the content file .env and re added variable_99=value
You can use file_put_contents and parse_ini_file like this follow below
function modifyEnv($path,$values = []) {
$env = [];
foreach(parse_ini_file($path) as $k => $value) {
if(in_array($k,array_keys($values))) {
$env[$k] = "$k={$values[$k]}";
}
}
return file_put_contents($path,implode(PHP_EOL,$env));
}
Then you can call like this, you can replace multiple .env variables by using array key, value. key is the old value and the value is the new value
modifyEnv('../../.env.securepay',[
'variable_99' => 'data_2051',
'variable_1' => 'data_2051'
]);

Bug fread in a txt file, read only one time

I'm creating a code to display the name of a server with enterprise rules, So for don't use Mysql i try a new things (for me) use php to read and rewrite files, that work perfectly for one part of my code and work perfectly but for the second he only read one time, and when i do a f5 the code don't increment.
He rewrite correctly because my file was at 000 and become 001
I try to use file() but he is disable since 7.0, try to use SplFileObject but it don't want to display anything and i don't like it because i understand nothing when i use it so i come back to fopen(),fread() and fwrite() and that don't work. I'm inPHP 7.3.1
The code that works :
<?php
if ( isset($_POST) AND !empty($_POST) ) {
$nom = "./config.txt";
$filez = fopen($nom, "r") or die("Unable to open file!");
$i = fread($filez,filesize($nom));
$year = getdate();
$idy = substr($year[year], 2);
$fichier = fopen("./resultsrv.txt", "w") or die("Unable to write file!");
for ($z; $z<$_POST['nbr']+1 ; $z++) {
$id = sprintf("%04d", $i+$z);
$nome = $_POST['type'].$_POST['OS'].$idy.$id."<br>" ;
echo $nome;
$nomewout = str_replace("<br>", ";", $nome);
fwrite($fichier,$nomewout);
}
$handle = fopen("./config.txt", "w") or die("Unable to write file!");
fwrite($handle,$id);
fclose($fichier);
fclose($handle);
}
?>
and the one that doesn't work because he doesn't increment :
<?php
if ( isset($_POST) AND !empty($_POST) ) {
$fileName = 'confchass.txt';
$read = fopen($fileName,"r");
$fn = fopen($fileName,"w+");
$i = fread($read,filesize($fileName));
$id = sprintf("%03d", $i+1);
echo "<div align='center'><h1>Le Chassis</h1>";
echo $_POST['Marque'].$_POST['DC'].$id;
echo "</div>";
fwrite($fn,$id);
fclose($read);
fclose($fn);
}
?>
I want he output a thing like XXXXXX001 and when i refresh or do a new POST from my forms he output XXXXXX002 and XXXXXX003 .... But he actualy output only XXXXXX001
The problem is that you open the file for reading and then for writing. But from the manual...
'w+' Open for reading and writing; place the file pointer at the
beginning of the file and truncate the file to zero length. If the
file does not exist, attempt to create it.
So this will blank out the file before you read the value from it.
To fix this (using your current method, you should read the value, then open it for writing and write the new value...
$read = fopen($fileName,"r");
$i = fread($read,filesize($fileName));
fclose($read);
$id = sprintf("%03d", $i+1);
echo "<div align='center'><h1>Le Chassis</h1>";
echo $id;
echo "</div>";
$fn = fopen($fileName,"w+");
fwrite($fn,$id);
fclose($fn);
You could shorten this by using file_get_contents() and file_put_contents().

Trying to build a file in PHP and use fwrite to file

trying to figure out how i can make a and save a file while including default info from another file. i tried include but it did not work. any suggestion on how to build this file?
<?php
$wrtID = $_POST["fileID"];
SQL statement here to get relevant info
mkdir("CNC/$wrtID", 0770, true);
?>
<?php
$batfile = fopen("CNC/$wrtID/$wrtID.bat", "w") or die("Unable to open file!");
$txt = "
#ECHO OFF
#ECHO **** Run NC-Generator WOODWOP 4.0 ****
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-sl.mpr
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-sr.mpr
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-tb.mpr
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-dc.mpr
#ECHO **** Done ****
";
fwrite($batfile, $txt);
fclose($batfile);
?>
<?php
$slfile = fopen("CNC/$wrtID/$wrtID-sl.mpr", "w") or die("Unable to open file!");
$txt = "
include("defaultcnc.php");
if ( additional file pats needed ) {
include("component-1.php");
}
";
fwrite($slfile, $txt);
fclose($slfile);
?>
I don't see a problem in the first block of code.
On the second block, the interpreter will consider the second double quotes to mean the end of the string $txt = " include(". So everything after that would produce a PHP error.
But even if you escape those the mpr file will have the string include("defaultcnc,php"); but not the actual contents of that file. For that you should do file_get_contents("defaultcnc.php").
something like:
<?php
$slfile = fopen("CNC/$wrtID/$wrtID-sl.mpr", "w") or die("Unable to open file!");
// set params to pass to defaultcnc.php
$value1 = 1;
$value2 = "I'm a text string";
$file = urlencode("defaultcnc.php?key1=".$value1."&key2=".$value2);
$txt = file_get_contents($file);
if ( additional file pats needed ) {
$txt .= file_get_contents("component-1.php");
}
fwrite($slfile, $txt);
fclose($slfile);
?>
I assume additional file pats needed means something to you. It should be a condition evaluating either true or false.

Odd Behavior when appending JSON file using PHP

So I have a JSON file containing basketball player information in the following format:
[{"name":"Lamar Patterson","team":1,"yearsLeft":0,"position":"PG","PPG":17},{"name":"Talib Zanna", "team":1,"yearsLeft":0,"position":"SF","PPG":13.1},....]
I want a user to be a able to add their own custom players to this file. To do this i try the following:
<?php
$json = file_get_contents('json/players.json');
$info = json_decode($json, true);
$info[] = array('name'=>$name, 'team'=>$team, 'yearsLeft'=>4, 'position'=>$position, 'PPG'=>$ppg);
file_put_contents('json/players.json', json_encode($info));
?>
This "sort of" works. But when I check the JSON file, I find that there are 3 new entries rather than 1:
{"name":"","team":null,"yearsLeft":4,"position":"","PPG":""},{"name":"","team":"3","yearsLeft":4,"position":"","PPG":""},{"name":"Jeff","team":null,"yearsLeft":4,"position":"C","PPG":"23"}
assuming $name="Jeff" $team=3 and $ppg=23 (populated via POST submission).
What's going on and how can I fix it?
You could try doing the following:
Untested code
<?php
if(!empty($name) && !empty($team) && !empty($position) && !empty($ppg)) {
$fh = fopen('json/players.json', 'r+') or die("can't open file");
$stat = fstat($fh);
ftruncate($fh, $stat['size']-1);//removes last ] char
fclose($fh);
$fh = fopen('json/players.json', 'a');
$info = array('name'=>$name, 'team'=>$team, 'yearsLeft'=>4, 'position'=>$position, 'PPG'=>$ppg);
fwrite($fh, ','.json_encode($info).']');
fclose($fh);
}
?>
This will append the only the new json to the file instead of opening the file, making php parse all the json and then writing it to the file again. In addition to that it will only store the data if the variables actually contain data.
Try this:
<?php
//get the posted values
$name = $_POST['name'];
$team = $_POST['team'];
$position = $_POST['position'];
$ppg = $_POST['ppg'];
//verify they're not empty
if(!empty($name) && !empty($team) && !empty($position) && !empty($ppg)) {
//Open the file
$fh = fopen('json/players.json', 'r+') or die("can't open file");
//get file info/stats
$stat = fstat($fh);
//final desired size after trimming the trailing ']'
$size = $stat['size']-1;
//file has contents? then remove the trailing ']'
if($size>0) ftruncate($fh, $size);
//close the current handle
fclose($fh);
// reopen the file for append
$fh = fopen('json/players.json', 'a');
//build your data array
$info = array('name'=>$name, 'team'=>$team, 'yearsLeft'=>4, 'position'=>$position, 'PPG'=>$ppg);
//if this is not the first item on file
if($size>0) fwrite($fh, ','.json_encode($info).']'); //append with comma
else fwrite($fh, '['.json_encode($info).']'); //first item on file
fclose($fh);
}
?>
Maybe your php config is not set to convert the post/get variables to global variables. This happened to me a couple of times so I rather create the variables I'm expecting from the post/get request. Also watch out for the page encoding, from personal experience you could be getting empty strings there.

PHP Write and Read from Text File

I have an issue with writing and reading to text file.
I have to first write from a text file to another text file some values which I need to read again. Below are the code snippets:
Write to text file:
$fp = #fopen ("text1.txt", "r");
$fh = #fopen("text2.txt", 'a+');
if ($fp) {
//for each line in file
while(!feof($fp)) {
//push lines into array
$thisline = fgets($fp);
$thisline1 = trim($thisline);
$stringData = $thisline1. "\r\n";
fwrite($fh, $stringData);
fwrite($fh, "test");
}
}
fclose($fp);
fclose($fh);
Read from the written textfile
$page = join("",file("text2.txt"));
$kw = explode("\n", $page);
for($i=0;$i<count($kw);$i++){
echo rtrim($kw[$i]);
}
But, if I am not mistaken due to the "/r/n" I used to insert the newline, when I am reading back, there are issues and I need to pass the read values from only the even lines to a function to perform other operations.
How do I resolve this issue? Basically, I need to write certain values to a textfile and then read only the values from the even lines.
I'm not sure whether you have issues with the even line numbers or with reading the file back in.
Here is the solution for the even line numbers.
$page = join("",file("text2.txt"));
$kw = explode("\n", $page);
for($i=0;$i<count($kw);$i++){
$myValue = rtrim($kw[$i]);
if(i % 2 == 0)
{
echo $myValue;
}
}

Categories