php file write arrays variables html not working - php

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);
?>

Related

Form input field not displaying previous data correct

With the following code I need to be able to enter a tracking pixel code which contains these " & ? characters.
With the below code it allows entry of the pixel in the textbox saving it and the resulting line in the file is correct.
However when it then reloads the pixel for display in the value in the form field it has been cut off.
<?php
if (isset($_POST["pixel"])) {
$fp = fopen("config.php", "w") or die("Unable to open file config file");
fwrite($fp, $_POST["pixel"]."\n");
fclose($fp);
}
$fp = fopen("configz.php", "r") or die("Unable to open config file");
$pixel = fgets($fp);
fclose($fp);
?>
<form method="post">
Pixel:<input type="text" name="pixel" value="<?=$pixel?>" />
<input type="submit" name="Save" value="Save">
</form>
You need to change below code
<input type="text" name="pixel" value="<?=$pixel?>" />
to
<input type="text" name="pixel" value='<?=$pixel?>' />
Add single '' around value as in your $pixel string you have "". It will break the string from the first occurrence of " in $pixel.
Edit
You can replace all single quote with double quotes.
JS
var b = a.replace(/'/g, '"');
where a will be your string.
PHP
$pixel = str_replace("'", '"', $pixel);
Update
To replace all double quotes with single quotes in form input.
var newVal = [];
$('#form_id *').filter(':input').each(function(){
var k = $(this).attr('name');
var v = $(this).val();
newVal[key] = v.replace(/'/g, '"');
});
You can loop through all the values of the form and get their name as a key, get all values, perform replace on all values and add key=>value pair in an empty array. In newVal you will have the desired output which you can use.
<?php
if (isset($_POST["pixel"])) {
$fp = fopen("config.php", "w") or die("Unable to open file config
file");
fwrite($fp, $_POST["pixel"]."\n");
fclose($fp);
}
$fp = fopen("configz.php", "r") or die("Unable to open config file");
$pixel = fgets($fp);
fclose($fp);
?>
<form method="post">
Pixel:<input type="text" name="pixel" value='<?=$pixel?>' />
<input type="submit" name="Save" value="Save">
</form>
Add a single quote instead of double quotes.
I have solved my issue by leaving all the code as it was originally and just changing the fgets line.
This allows the field to have single or double quotes in it and displays the data correctly.
not letting me post it. it changes it here.

Get HTML data and append to a .txt file in server with PHP

I have been trying to get the data input from <teaxtarea> and append it in a .txt file in the server everytime someone inputs there. The server-side language is currently PHP. I have been trying for a possible solution online or in the tutorials, but likely end up with unsatisfied result. I am pretty sure it's a really simple thing, but as a total newbie (just started PHP few days ago) I am really lost right now.
Help will be much appreciated.
I have tried so many methods, now a bit lost. Here's something I have tried and failed. -
<?php
$myfile = "input.txt";
$txt = $_POST["text"];
fopen($myfile, "a");
fwrite($myfile, $txt);
fclose($myfile);
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "POST">
<textarea name="text"></textarea>
<input type="submit"></input>
</form>
</body>
</html>
Please refer to the documentation for fopen and fwrite.
fopen will return a file pointer which you will need to pass to any functions like fwrite and fclose. Passing the file name will not work.
Also, using "a" in fopen requires the file to exist. Change it to "a+" to create it if needed and make sure the script has permission to do so.
Finally, if you want new form submissions to go on a new line, you will need to add new line yourself because "a" will put the file pointer to the end of the file only. It will not add newlines for you.
This should work:
<?php
if (isset($_POST["text"])) {
$txt = $_POST["text"];
$fp = fopen("text.txt", "a+");
fwrite($fp, $txt . PHP_EOL);
fclose($fp);
}
?>
<!DOCTYPE html>
<html>
<body>
<form method = "POST">
<textarea name="text"></textarea>
<input type="submit"></input>
</form>
</body>
</html>
As an alternative to the fopen, fwrite, fclose combo, you could also just use
file_put_contents("text.txt", $_POST["text"] . PHP_EOL, FILE_APPEND);
Your form action is wrong.
You could leave it blank, because the target php-code is on the same page, or use
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
And like Gordon said, you have to define a file, e.g.
$filePath = './file/path.txt';
$file = fopen($filePath, 'a');
frwite($file, $message);
fclose($file);

how to handling non English chars with php

I have code in php that create file with name that user input like below
html
<form method="post">
<input type="text" name="file">
<input type="submit">
</form>
php
$file = $_POST['file'].'.php';
$f = fopen($file, 'w');
fclose($f);
the problem appear when user use non-english chars
example user input = اللغة العربيه
resault = ظ…ط±ط§ظ‡ظ‚ظˆ-ط§ظ„طھط§ظٹطھظ†ط.php
but it should be = اللغة العربيه.php
Trying to create files with non-english filenames can be quite hard.
Easiest solution is to not use such filenames at all, but encode all filenames e.g. with urlencode:
$filename = $_POST['file'].'.php';
$encoded_filename = urlencode($filename);
$f = fopen($encoded_filename, 'w');
fclose($f);
This will not affect English characters and will allow creating filenames using any language.
Note that each filesystem will have some limits on how long filesnames can be, so if $encoded_filename becomes too long this will not work.

Modifying a text file with 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

PHP best way to output certain data to text?

Ok, so I have a form that takes a username and a code. This is then passed to php for processing. I am not super php saavy, so I want to be able to take a specific portion of the out put and write it to a text file, this form would be used over and over, and I want the text to be appended to the file. As you can see from the output I'm looking to capture, it's basically writing to some code that will be used for usernames in a css. So here is what I have...
The HTML Form
<html><body>
<h4>Codes Form</h4>
<form action="codes.php" method="post">
Username: <input name="Username" type="text" />
Usercode: <input name="Usercode" type="text" />
<input type="submit" value="Post It!" />
</form>
</body></html>
The PHP
--><html><body>
<?php
$Usercode = $_POST['Usercode'];
$Username = $_POST['Username'];
echo "You have recorded the following in our system ". $Username . " " . $Usercode . ".<br />";
echo "Thanks for contributing!";
echo .author[href$="/$Username"]:after {
echo content: "($Usercode)"
echo }
?>
</body></html>
All that I would like to be written to the text file would be this portion..
--> .author[href$="/$Username"]:after {
content: "($Usercode)"
}
Basically, the text file would have line after line of that exact same code, but with different usernames and usercodes. Hopefully, the variable $Usercode and $Username can also be captured and written into the output in the manner that I have it written. I'm just baffled by output buffering in php and clean and flush etc, and fwrite doesn't seem to be able to write without wiping a file clean each time it writes to it. I may be wrong of course. Anyone care to help?
Try this:
<?php
$output = "--> .author[href=$Username]:after { \n"
."content: ($Usercode)\n"
."}";
$fp = fopen($file, 'a');
fwrite($fp, $output);
fwrite($fp, "\n");
fclose($fp);
?>
The flag a will open already a text file and place the pointer to the end of file, so this will not overwrite your already file, more information in fopen.
You can use the function file_put_contents($file, $data, FILE_APPEND); where $file is the path of the file you are writing to, data is the whatever value you are writing to the file. This assumes you are using php5. If not, you will have to create a handle with fopen, write to the file with fwrite and end with fclose to close the file pointed to in your fopen handle.

Categories