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

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.

Related

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().

Adding a character beginning and end of each line to text file in PHP

I have a 'text.txt' file This text file has 1000 different line and I want to add a beginnig of each line " and also add end of each line ",
Block quote
Please help me
You can use file to open a file and make it an array per line.
Then loop it and add the " and save it again.
$arr = file("text.txt");
foreach($arr as &$line){
$line = '"' . $line . '"';
}
unset($line); //just in case and a good thing to remember in other projects
file_put_contents("text.txt", implode(PHP_EOL, $arr)); // write file with new line separating the array items.
<?php
$str = 'sometext';
echo '"'.$str.'"';
//expected output
"sometext"
?>
You can concat them using [period] operator. How to concat string in php
//open file
$myfile = fopen("logs.txt", "a") or die("Unable to open file!");
$txt = "user id date";
$txt = "'".$txt."'"; //add concatenation here
//write
fwrite($myfile, "\n". $txt);
fclose($myfile);

Session data to text file showing nothing

I have created something that once text is put inside of a text box and submit is pressed it sends this to a server and it is then stored in a session. On the press of another button you can retrieve this text and it is then transferred from the session to a txt file.
Yesterday I had this working and it was printing to my txt file but now all of a sudden it wont do it at all, can anyone spot any issues that would cause this?
This is ran when the retrieve button is pressed:
<?php session_start(); ?>
<?php
print_r($_SESSION ["input_data"]);
$myfile = fopen("TestingOut.txt", "a+") or die("Unable to open file!");
$txt = $_SESSION["input_data"];
fwrite($myfile, $txt);
fclose($myfile);
?>
I have narrowed it down to the $_SESSION["input_data"] part as it will print some random text in place for he session as seen above.
This is the creation of the session array:
<?php session_start(); ?>
<?php
$_SESSION["input_data"][] = $_POST["input"];
echo $_POST["input"];
?>
Many thanks to #marekful , I was tryign to print an array into a text file, I used implode() to fix this:
$strings = implode(" ", $_SESSION["input_data"]);
$myfile = fopen("TestingOut.txt", "a+") or die("Unable to open file!");
$txt = $strings;
fwrite($myfile, $txt);
fclose($myfile);

How to write a html file using PHP?

I used below HTML code and php code to Write new files.
<html>
<body>
<form action="write.php" method="get">
ID : <input type="text" name="ID"><br>
<input type="submit">
</form>
</body>
</html>
<?php
$myfile = fopen($_GET["ID"] , "w") or die("Unable to open file!");
$txt = "Your user ID =";
fwrite($myfile, $txt);
$txt = $_GET["ID"];
fwrite($myfile, $txt);
fclose($myfile);
?>
If I submit TEST to html form , php code writes a file named "test". it hasn't a file extension.
How to write "TEST.html" with above code.?
Add the extension to the filename before opening the file:-
$filename = $_GET["ID"] . '.html';
$myfile = fopen($filename, "w") or die("Unable to open file!");
Note You are opening up yourself to all kinds of security issues here.
just use this code:-
fopen($_GET["ID"].'.html' , "w")
You need to add .html with a !empty() check there, like below:-
<?php
if(!empty($_GET['ID'])){ // check first that ID is coming or not
$myfile = fopen($_GET["ID"]."html" , "w") or die("Unable to open file!");
$txt = "Your user ID =";
fwrite($myfile, $txt);
$txt = $_GET["ID"];
fwrite($myfile, $txt);
fclose($myfile);
}
?>
To open and read this file:-
<?php
if(!empty($_GET['ID'])){ // check first that ID is coming or not
$myfile = fopen($_GET["ID"]."html", "r") or die("Unable to open file!");
echo fread($myfile,filesize($_GET["ID"]));
fclose($myfile);
}
?>
OR:-
<?php
if(!empty($_GET['ID'])){ // check first that ID is coming or not
$file = fopen($_GET["ID"]."html","r") or die("Unable to open file!"); ;
while(! feof($file)){
echo fgets($file). "<br />";
}
fclose($file);
}
?>
Note:-
In my opinion you need .txt rather than .html.An HTML file with text like test really have no mean, or server any useful purpose. BTW it's up-to-you what extension you want. I just gave my opinion.

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

Categories