Modifying a text file with php - php

I have two webpages a.php and b.php. The submitted values in texboxes will be written to a text file.
a.php :
<html>
<?php
if (isset($_POST['Submit1'])) {
$aa = $_POST['alpha'];
$f = fopen("text.txt", "w");
fwrite($f,$aa."\n");
}
else
{
$f= fopen("text.txt",'r');
while ((!feof($f)) && ($found == 0)) {
list($aa)=fscanf($f,"%f[^\n]");
}
}
fclose($f);
?>
<form action="a.php" name="Calculation" method="post">
Alphabet: <INPUT TYPE ="TEXT" id="alph" Name "alpha" VALUE="<?PHP print $aa; ?>">
<Input Type = "Submit" Name = "Submit1" Value ="Save Parameters">
</form>
</html>
and b.php is:
<!DOCTYPE html>
<html>
<?php
if (isset($_POST['Submit1'])) {
$bb = $_POST['beta'];
file_put_contents("text.txt", $bb."\n" , FILE_APPEND);
}
else
{
$f= fopen("text.txt",'r');
while ((!feof($f)) && ($found == 0)) {
list($aa)=fscanf($f,"%f[^\n]");
list($bb)=fscanf($f,"%f");
}
}
fclose($f);
?>
<form action="b.php" name="Calculation" method="post">
Alphabet: <INPUT TYPE ="TEXT" id="betaa" Name ="beta" size="5" VALUE="<?PHP print $bb; ?>">
<Input Type = "Submit" Name = "Submit1" Value ="Save Parameters">
</form>
</html>
The codes work fine and the values in the text boxes will be written to a textfile if I enter the first valu in a.php text box and the second value in b.php textbox. For example if I put aa in the textbox of a.php and bb in the text box of b.php I will get
aa
bb
in my text file. However if I go back to my a.php file and put a new value in its text box I will loose bb. Is there a way to only change the value of the first line of the text box and keep the bb in second line of the text box?
. The problem is that I will lose the values of my b.php script if I add a new value. I don't want to add to the number of lines in the text file. I was wondering if there is a way to rewrite on aa with cc for example.

You're overwriting your file in a.php using the w switch.
Use the a switch to append.
$f = fopen("text.txt", "a");
Consult the manual:
http://php.net/manual/en/function.fopen.php
Or, do as you did in the other file (b.php) using file_put_contents()
file_put_contents("text.txt", $bb."\n" , FILE_APPEND);
^^^^^^^^^^^
it does the same thing.
Edit:
"I have a webpage that has several text boxes that need to be filled and the values are saved in a text file when the submit button is hit. Then there is another webpage that has several text boxes as well that need to be filled out and the values will have to be added to the same text file.
So if the user after pressing the submit button decides to change a value of one text box in a.php and then hit submit again I will lose all the information in bb.php unless I add more lines to my text file with the new information."
An alternate method would be to use two seperate and different filenames while keeping what you have now.
Here is an example, and concatenating the files:
<?php
$file1 = file_get_contents('file1.txt');
$file2 = file_get_contents('file2.txt');
$show_all = $file1 . $file2;
echo $show_all;
I used file_get_contents() in this example, since I do not know how you are presently showing the content in your webpage.
Sidenote:
If you want to add a line break between both, use <br>.
$show_all = $file1 . "<br>" . $file2;
or just a simple space:
$show_all = $file1 . " " . $file2;

You can use json function to manipulate with vars independently:
$f = json_decode(file_get_contents("tt.txt"));
$f['aa']= $_POST['alpha'];
file_put_contents("tt.txt", json_encode($f));
and change to bb in 2nd file. To read just
$f = json_decode(file_get_contents("tt.txt"));
echo $f['aa'].' '.$f['bb'];

To change only some specific lines of your file you can use:
$file = "text.txt";
$aa = $_POST['alpha'];
$rows_of_file = file($file); // put your file in an array line by line
$rows_of_file[0] = $aa; // 0 indicate the first line of the file
file_put_contents($file, implode($rows_of_file)); //rewrite the content with the new changes
So you can change aa in cc, and bb remains unchanged

Related

php file write arrays variables html not working

I am trying to make a website where you input a value to order food. In php i am trying to make it create a txt file that i can view. I have gotten it to make the file, but instead of a number, it simply displays 'Fries: Array' and the 'Array' should be a number. My php and HTML code is as follows...
HTML:
<input type="number" name="Fries" min="0" max="69"><br>
PHP:
<?php
$path = "Fries.txt";
$fh = fopen("Fries.txt", "w") or die("Unable to open file!");
$fries = array(['Fries']);
$string = 'Fries: '. strval($fries[0]);
fwrite($fh, $string);
fclose($fh);
?>`
If anyone can tell me how to get php to read HTML form data, that wiuld be great
Assuming that you're aware of all of the potential pitfalls of taking user input and writing it to a file without any type of validation: square brackets in PHP are a shortcut for defining a new array. So what you've written is equivalent to:
$fries = array(array('Fries'));
Also, you're assigning your new array the string value "fries," when you say you're trying to get this from your user input. Try the following:
...
$fries = 'Fries: ' . $_REQUEST['Fries'];
fwrite($fh, $string);
...
No need to use strval() - value is already a string.
And as far as validation, you may want to add the following before you assign your $fries variable:
if (is_numeric($_REQUEST['Fries'] && $_REQUEST['Fries'] >= 0 && $_REQUEST['Fries'] <= 69)
HTML:
<form method="post">
<input type="number" name="fries" min="0" max="69"><br>
<input type="submit" name="submit">
</form>
PHP:
<?php
$path = "Fries.txt";
$fh = fopen($path, "w") or die("Unable to open file!");
$string = 'Fries: '. filter_input(INPUT_POST,'fries');
fwrite($fh, $string);
fclose($fh);
?>

how to take user input in php other than get or post method

I was trying to write a code for fizz buzz game...and i completed it...but the problem is i need to take input from the user, my code only works for the input that i have declared inside the code...could anyone specify any way that i can take input from user...post method didn't work..
my code is as follows...
<html>
<body>
<form method="post">
enter Value of A
<input type="text" name="A">
enter value of B
<input type="text" name="B">
enter value of N
<input value="text" name="N">
</form>
</body>
</html>
<?php
$N=$_POST["N"];
$A=$_POST["A"];
$B=$_POST["B"];
while($N!=100) {
if($N%$A==0 & $N%$B==0) {
echo"FizzBuzz\n";
}
elseif ($N%$A==0) {
echo"Fizz\n";
}
elseif ($N%$B==0) {
echo"buzz\n";
}
else
echo"$N \n";
$N=$N+1;
}
?>
After the OP made it clear that it should look like a console application that takes input from a file, the answers I can prepare are several:
First of all there is no need of HTML, since there will be no real user that will open the web browser, because everything will happen from the CLI, and there will be no input, but a file.
To take a file as input you may need fgets(). The file can be sent from the standard input, so fgets(STDIN) will do the work. However, this really depends how the file is formatted.
In one ideal case, I have file test.txt which has each on separated lines:
50
100
200
To use test.txt as standard input, you may need:
<?php
$input = explode("\r\n",stream_get_line(STDIN, 1024));
//Explode the news lines as array, to assign then as N, A and B
$N=$input[2];
$A=$input[0];
$B=$input[1];
while($N!=100) {
if($N%$A==0 & $N%$B==0) {
echo"FizzBuzz\n";
}
elseif ($N%$A==0) {
echo"Fizz\n";
}
elseif ($N%$B==0) {
echo"buzz\n";
}
else
echo"$N \n";
$N=$N+1;
}
?>
Now you run the script from the console as
$ php path/to/file/file.php < path/to/input/test.txt
Ofcourse, you can make costumizations where openning the file is waiting for input which can be a file name
$stdin = fgets(STDIN); and then $ php path/to/file/file.php will wait for something to be typed.
If it's a valid file name you can use file_get_contents($stdin);
Or, you can use command line arguments, available in CLI mode $argv array:
$file = file_get_contents(__DIR__.DIRECTORY_SEPARATOR.$argv[1]);
$input = explode("\r\n", $file);
This will open the file, with the given name as first parameters, in the directory of the PHP file
$ php path/to/file/file.php test.txt

PHP - Stop while loop after reading every single line from text file

I want the Code below to read individual line of text from dataFile.txt and show it in input field.
Problem is After reading first line from text document it shows all remaining lines of text from text file into input field. But on clicking submit it should show second line only then again on submitting it should show third line only, inside input field. please help.
<?php
$file = __DIR__."/dataFile.txt";
$f = fopen($file, "r");
$array1 = array();
<form action="datagGet.php" method="get">
<input type="text" value="
<?php while ( $line = fgets($f, 100) )
{
$nl = mb_strtolower($line);
echo $nl;
if(isset($_GET['done']))
{
$nl++;
}
else
{
break;
}
}
?>"
name="someText">
<input type="submit" name="done" >
</form>
You have several problems with you code. And the first comment above points to many of the. Key is the fact that the $_GET['done'] is set for the form submit and therefore you will echo all the lines of the output. It never breaks.
Also there is the fact that you are opening the file for reading each submit of the form. Although I don't see a simple way around this unless you store the file contents between requests.
One possible option is to use 'file()' to read the entire contents into an array. And then use sessions to store which line has been read. Then on each submit, look for the index of the array from the session read; advance it by one read the file again and return that line. Wow wasteful. But okay for simple site.
so use file to get the lines in an array.
output the first line into the value.
store the next index to be read in the $_SESSION variable like $_SESSION['next_line'] = 1
then upon further submissions. read it all back in. look up the 'next_line', and output that line.
so, for example
$array = file('your file name');
$output = $array[0];
if (isset($_SESSION['next_line']))
$_SESSION['next_line'] = intval($_SESSION['next_line']) + 1;
else
$_SESSION['next_line'] = 1;//prime the pump
echo the form with $output
then rinse and repeat. e.g. read, get output (next_line) with file, set $_session = next_line + 1; render output in form.
ps. some extra notes
* of course you'll need to start session on each request.
* you'll need to check if the $_SESSION['next_line'] is set. if not, set it to 1 (prime it)

Comparing between data from a file and from a form fails even though it's the same

I have a problem with my webpage. I have this admin.txt file that contains "foo", and "bar" on the next line. Now on my webpage is a form where I must input two values, and when submitted will check if the values I inputted on the text inputs are equal with the values in the text file, but always returns fail even if i typed in the same values with the text file which is foo and bar. Check my codes:
index.php
<?php
<form method="post" action="check.php">
<input type="text" name="text1">
<input type="text" name="text2">
<input type="submit">
?>
check.php
$location = "txt/admin.txt";
if ( file_exists( $location )) {
$page = join("",file("$location"));
$txt = explode("\n", $page);}
$text1 = $_POST['text1'];
$text2 = $_POST['text2'];
if ($text1==$txt[0] && $text2==$txt[1]){
echo "success.";
}
else
echo "fail";
There may be additional invisible line break characters that cause the comparison to fail.
In Windows for example, the line break is \r\n, meaning your explode() will leave the \r in the data.
Always use trim() on data coming from files.
Alternatively, you can also use the file() function with the FILE_IGNORE_NEW_LINES parameter.

Issue Passing JS variable to PHP include file

I have a php file where I am using it to setup dynamically generated pages based on the input variables. It starts on and index.html page where the variables are gathered some of which are not simple strings but complex Google Earth objects. On the submit of that page it is posted to another page and you are redirected to the created file. The trouble is coming when I try to use that variable within the php include file that is used to generate the pages.How do i properly get a variable from this form and then pass it through to be able to use it on the new generated page. Here is what I am trying currently.
On the click of this button the variable flyto1view is set.
$("#flyto1").click(function(){
if (!flyto1view){
flyto1view = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
$("#flyto1view1").val(flyto1view)
}
else {
ge.getView().setAbstractView(flyto1view);
}
});
Then from here I have tried setting the value to an hidden field but Im not sure if that kinda of variable has a value that can be set like that. Whats the best way to get this variable to here after post
<?
if (isset($_POST['submit']) && $_POST['submit']=="Submit" && !empty($_POST['address'])) {//if submit button clicked and name field is not empty
$flyto1view1 = $_POST['flyto1'];
$address = $_POST['address']; //the entered name
$l = $address{0}; // the first letter of the name
// Create the subdirectory:
// this creates the subdirectory, $l, if it does not already exists
// Note: this subdirectory is created in current directory that this php file is in.
if(!file_exists($l))
{
mkdir($l);
}
// End create directory
// Create the file:
$fileName = dirname(__FILE__)."/$address.html"; // names the file $name
$fh = fopen($fileName, 'w') or die("can't open file");
// The html code:
// this will outpout: My name is (address) !
$str = "
<? php include ('template.php') ?>
";
fwrite($fh, $str);
fclose($fh);
// End create file
echo "Congradualations!<br />
The file has been created.
Go to it by clicking here.";
die();
}
// The form:
?>
Firstly. creating files from user input is pretty risky. Maybe this is only an abstract of your code but doing a mkdir from the first letter of the input without checking that the first letter is actually a letter and not a dot, slash, or other character isn't good practice.
Anyway, on to your question. I would probably use $_GET variables to pass to the second file. So in the second file you use <?php $_GET['foo'] ?> and on the first file you do:
echo "Congradualations!<br />
The file has been created.
Go to it by clicking here.";
You could also echo the variable into your template like so:
$str = '
<?php
$var = \'' . $flyto1view1 . '\';
include (\'template.php\')
?>';

Categories