Writing text to .txt file using PHP - php

So I have page.txt which looks like this:
<textarea name="msg" rows="1"></textarea>
<form id="post" name="post" action="storeText.php" method="post">
<input class="button" type="submit" value="Set news now"/>
</form>
I also have storeText.php which looks like this:
<?php
$filename = 'posts.txt';
$msg = (isset($_POST['msg']) ? $_POST['msg'] : null);
// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {
// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
// Write $somecontent to our opened file.
if (fwrite($handle, $msg) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote ($msg) to file ($filename)";
fclose($handle);
} else {
echo "The file $filename is not writable";
}
?>
Now it should write the text onto posts.txt but it always says "Success, wrote () to file...". Notice the empty parenthesis which should have my input.
Any ideas? Thanks!

<textarea name="msg" rows="1"></textarea>
<form id="post" name="post" action="storeText.php" method="post">
<input class="button" type="submit" value="Set news now"/>
</form>
If the textarea is outside of the form block it won't be sent. So your html should look like:
<form id="post" name="post" action="storeText.php" method="post">
<textarea name="msg" rows="1"></textarea>
<input class="button" type="submit" value="Set news now"/>
</form>

Your <textarea> element is outside of your <form> tags.
<textarea>should either go inside the form tags or you need to specify a form attribute to link the input to a form e.g. <textarea form="myForm"> (the latter may not work in older browsers, though, best to put it inside the <form> tag if you can).
That's why your $_POST['msg'] is null

Related

How can I get the output for form without the page changing

I am trying to get information from textarea to be converted to a .py file.
Here's my file https://jsfiddle.net/girlwhocancode/68mb49gq/
<form action=action.php method="post">
<center>
<textarea placeholder="Code you want to execute in python..."></textarea>
</center><br/>
<center><input type="submit" class="button_example"></center>
</form>
and this is my php file:
<?php
$path = #PATH;
if (isset($_POST['field1'])) {
$fh = fopen($path,"a+");
$string = $_POST['field1'];
fwrite($fh,$string); // Write information to the file
fclose($fh); // Close the file
}
?>
For some reason my php isn't working and I have no idea how to keep the same webpage after submitting
Try this:
<form action="action.php" method="post">
<center>
<textarea name="script" placeholder="Code you want to execute in python..."></textarea> //added name
</center><br/>
<center><input name="submit" type="submit" class="button_example"></center>
</form> // added name submit
in php
<?php
$path = #PATH;
if (isset($_POST['submit'])) {
$fh = fopen($path,"a+");
$string = $_POST['script'];
fwrite($fh,$string); // Write information to the file
fclose($fh); // Close the file
}
?>
Remember that in php $_POST/$_GET keys are always your form field
names

PHP SELF is automatically called on page load

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$fn=$_POST["filename"];
$content=$_POST["txt"];
$fp= fopen("abc.txt", "w") or die("unable to open file");
fclose($fp);
}
?>
<html>
<head>
<title>Files</title>
</head>
<body>
<center>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post" id="show">
<input type="text" name="filename" placeholder="File Name"><br>
<textarea name="txt" id="txtarea" id="txtarea" rows="20" cols="50" placeholder="Text goes here..."></textarea><br>
<input id="ixtbtn" type="submit" id="tabuttton" value="Done">
</form>
</center>
</body>
</html>
Php is automatically getting called on page load. But I need it to be called when submit button is pressed.
<?php
if (isset($_POST['submitted']))
{
$fn=$_POST["filename"];
$content=$_POST["txt"];
$fp= fopen("abc.txt", "w") or die("unable to open file");
fclose($fp);
}
?>
<html>
<head>
<title>Files</title>
</head>
<body>
<center>
<?php echo "<form action='" . htmlspecialchars(#_SERVER['PHP_SELF']) . "' method='post' id='show'>"; ?>
<input type="text" name="filename" placeholder="File Name"><br>
<textarea name="txt" id="txtarea" id="txtarea" rows="20" cols="50" placeholder="Text goes here..."></textarea><br>
<input id="ixtbtn" type="submit" id="tabuttton" value="Done" name='submitted'>
</form>
</center>
</body>
</html>
Played with your code a bit and noticed two things: (1) your statement is outside your php code block and in straight html. (2) On my system (Firefox or Safari on OSX) that meant that the php $_SERVER['PHP_SELF'] was never translated back to php, it was treated as text and the post command kept posting to the server looking for a URL starting with the php If I use echo inside php to output your HTML, the variables ($_SERVER) are not substituted and go in as straight text. So I put your html into a string variable first to translate the variables and then echoed your html. Saved the file as an PHP file instead of as an html file and your code worked just fine. So, four net changes.
Move the closing php statement (?>) to the end of the file
copy the HTML into a php string
$outputString = "";
$outputString = $outputString.'<!DOCTYPE html>';
$outputString = $outputString.'<html><head><meta charset="utf-8"><title>Files</title>';
$outputString = $outputString.'</head><body><center>';
$outputString = $outputString.'<form action="'.$_SERVER['PHP_SELF'].'" method="post" id="show">';
$outputString = $outputString.'<input type="text" name="filename" placeholder="File Name"><br>';
$outputString = $outputString.'<textarea name="txt" id="txtarea" id="txtarea" rows="20" cols="50" placeholder="Text goes here..."></textarea><br>';
$outputString = $outputString.'<input id="ixtbtn" type="submit" id="tabuttton" name="myButton" value="Done">';
$outputString = $outputString.'</form></center></body></html>';
Echo the string
Save as .php instead of .html

Php button action event needed

How do i implement button click php when either one of the buttons is clicked? I am trying to do is, if sumbit button is clicked the php script below shows it written to a file and if view comments is hit shows comments
<html>
<body>
<form action="http://localhost/class/assignment10.php" method="post">
User Name: <input type="text" name="uname"><br>
User Comments: <textarea type ="text" name="tcomment"></textarea><br>
<input type="submit" value="Submit Comments"/>
<input type="submit" value="View Comments"/>
</form>
</body>
</html>
I have two form buttons IF submit comments is clickedthe php code should write the user’s name and comments to a text file (use fputs function to write to a file. Also you should insert a newline after each name and each comment). When user’s name and comments are successfully recorded, php should direct
On the other hand, if a user clicks on the ‘view all comments’ button, the php code should
show all users and their corresponding comments (use fgets function)
<html>
<head>
<title>PHPLesson10</title>
</head>
<body>
<?php
// Collect user name and add a line break at the end.
$customer = $_POST['uname']."\n";
// Collect comment and add a line break.
$comments = $_POST['tcomment']."\n";
$file = fopen("C:/data/feedback.txt", "a");
If ($file) // if the file open successfully
{
// Write the variables to the file.
fputs($file, $customer);
fputs($file, $comments);
fclose($file);
}
Else
{
Echo "Please try again.";
}
?>
</body>
</html>
<?php
// Open the file feedback for reading
$file = fopen("C:/data/feedback.txt", "r");
// While the end of the file has NOT reached
While (!feof($file))
{
// Print one line of file
Echo fgets($file);
Echo "<br />";
}
// close the connection
fclose($file);
?>
Your submit buttons should like below :
<input type="submit" name="submit_comment" value="Submit Comments"/>
<input type="submit" name="view_comment" value="View Comments"/>
And your php code for each buttons should like below:
<?php
if(isset($_POST['submit_comment']))
{
//the php code will be here for save comment
}
if(isset($_POST['view_comment']))
{
//the php code will be here for view comment
}
?>
use name attribute on buttons
<input type="submit" value="Submit Comments" name="btn_submit"/>
<input type="submit" value="View Comments" name="btn_view"/>
then on php you can check something like
if (isset($_POST['btn_submit']))...
or
if (isset($_POST['btn_view']))...
Best regards,
Nebojsa
For buttons, I usually use <button> tags and not <input> tags, as long as you're using <!doctype html> for HTML5.
<form action="http://localhost/class/assignment10.php" method="post" id="commentForm">
<button type="submit" name="action" value="submit" form="commentForm">
Submit Comments
</button>
<button type="submit" name="action" value="view" form="commentForm">
View Comments
</button>
</form>
Then use PHP to figure out what the user clicked like this:
<?php
$action = $_POST["action"];
if ($action == "submit") {
// submission code
}
if ($action == "view") {
// viewing code
}
else {
die("Your request could not be completed.");
}
?>
First give your submit buttons a name like so:
<input type="submit" name="button1" value="Submit Comments"/>
<input type="submit" name="button2" value="View Comments"/>
and then use this PHP:
<?php
if (isset(#$_POST['button1'])) {
//Code to execute
}
if (isset(#$_POST['button2'])) {
//Code to execute
}
?>

PHP write data from HTML to text file

I need to write some data from HTML form to data.txt file (the txt file have 777 permissions)
The HTML that I use is index.html:
<form action="index.php" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
And the PHP file is index.php:
<?php
$txt = "data.txt";
if (isset($_POST['field1']) && isset($_POST['field2'])) { // check if both fields are set
$fh = fopen($txt, 'a');
$txt=$_POST['field1'].' - '.$_POST['field2'];
fwrite($fh,$txt); // Write information to the file
fclose($fh); // Close the file
}
?>
But when I use the form to save the data, it show me a message box to download the index.php
what I am doing wrong?

Edit XML via HTML Form (PHP)

I'm trying to create a form that will let you edit the contents of an xml tag. i currently have a form.php:
<?php
$data=simplexml_load_file('welcome.xml');
$welcome=$data->item->name;
?>
<form method="post">
<textarea name="name"><?php echo $welcome ?></textarea>
<br>
<input type="submit" name="submit" value="submit">
</form>
<?php
if(isset($_POST['submit'])) {
$data=simplexml_load_file('welcome.xml');
$data->item->name=$_POST['name'];
$handle=fopen("welcome.xml","wb");
fwrite($handle,$xml->asXML());
fclose($handle);
}
?>
and welcome.xml:
<welcome>
<item>
<name>$welcome</name>
</item>
</welcome>
when i press submit it doesn't save what's entered, it just refreshes the page and deletes whatever the value in the xml file was before..
UPDATE
The form works now, but I've added a reset button, i need it to clear the xml file so it only has the <welcome> tags. I've changed $data->item->name=$_POST['welcome']; to $data=''; but it deletes the text and keeps the tags still.
You can do it with simplexml.
To read data from xml:
$data = simplexml_load_file('welcome.xml');
$welcome = $data->item[0]->name;
And to write data:
$data = simplexml_load_file('welcome.xml');
$data->item[0]->name = $_POST['welcome'];
$handle = fopen("welcome.xml", "wb");
fwrite($handle, $xml->asXML());
fclose($handle);
EDIT:
For the question in the comment:
<?php
if(isset($_POST['submit'])) {
$data=simplexml_load_file('welcome.xml');
$data->item->name=$_POST['name'];
$handle=fopen("welcome.xml","wb");
fwrite($handle,$data->asXML());
fclose($handle);
}
$data=simplexml_load_file('welcome.xml');
$welcome=$data->item->name;
?>
<form method="post">
<textarea name="name"><?php echo $welcome ?></textarea>
<br>
<input type="submit" name="submit" value="submit">
</form>

Categories