Saving data from HTML form on server? - php

How do i save data from a HTML form on a server?
Here is my code:
<form action="?action=save" name="myform" method="post">
<textarea class="textBox" name="mytext"> </textarea>
<input type="submit" class="save" value="save"/>
Thanks in advance.

You will need to change the action name to point to where the PHP code will be. I put my PHP code on the same page as my HTML and changed the action to save.php (that's my file name where the PHP is).
This is my save.php file where everything is.
<?php
// Check if form is submitted and we have the fields we want.
if(isset($_POST["mytext"]))
{
$file = "data.txt";
$text = $_POST["mytext"];
// This file will create a data.txt file and put whatever is in the POST field mytext into the text and put a new line on the end.
// The FILE_APPEND allows you to append text to the file. LOCK_EX prevents anyone else from writing to the file at the same time.
file_put_contents($file, $text . "\r\n", FILE_APPEND | LOCK_EX);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Save POST Data</title>
</head>
<body>
<form action="save.php" name="myform" method="post">
<textarea class="textBox" name="mytext"></textarea>
<input type="submit" class="save" value="save"/>
</body>
</html>

Easiest way its set action on save.php and in this file put
<?php
if(isset($_POST)){
file_put_contents('file.txt', json_encode($_POST));
}

You can handle the submit event by js, and send the data to server by using Ajax or fetch. Then in your server side, build an API to catch the request and store data in database or any file you want to store your data.
Best

Related

Edit .txt file using forms in html php

I have written a program in php,html. I have created a form and I can save the form inputs in a .txt file.The thing is I need to write a code where I can edit my .txt file inputs and save them again with the changes. Can you help me out? This is the code I have written.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="post" action="bug.php">
<label>Emri produktit:</label>
<input type="text" name="emriprod" id="emriprod">
<label>Versioni</label>
<input type="text" name="versioni" id="versioni">
<label>Frekuenca</label>
<input type="text" name="frekuenca" id="frekuenca">
<input type="submit" value="Submit">
</form>
</body>
</html>
bug.php
<?php
$emriprod=$_POST["emriprod"];
$versioni=$_POST["versioni"];
$frekuenca=$_POST["frekuenca"];
$fp=fopen("bug.txt","a");
$string=$emriprod." ".$versioni." ".$frekuenca."\r\n";
fwrite($fp, $string);
fclose($fp);
echo "Te dhenat u ruajten ne file";
?>
You can store the data with special characters to separate the fields .
$string = $emriprod."##".$versioni."##".$frekuenca."\r\n";
Retrieving the data
$file_data = file_get_contents('bug.txt');
$data = $explode('##', $file_data); //separating the string to array
After you editing the existing data, update the file like below
file_put_contents('bug.txt',str_replace('old data','new_data',file_get_contents('bug.txt')));
Hope this helps to solve your problem.

Replacing HTML post action with PHP

Edit: Just to clarify, I only want to open a file and change some text.
I have a basic HTML page with a form, and I want to change the POST action programatically with PHP.
I have this PHP script which I got from another post:
<?php
$file = file_get_contents($argv[1]);
$startPoint='action="';
$endPoint='"';
$newText='phpfile.php';
$newFile = fopen($argv[1], "w");
fwrite(
$newFile,
preg_replace(
'#('.preg_quote($startPoint).')(.*)('.preg_quote($endPoint).')#si',
'$1'.$newText.'$3',
$file
)
);
fclose($newFile);
?>
..and this HTML file:
<html>
<form method="POST" action="https://www.example.com/">
<input type="text" name="email">
<input type="password" name="password">
<input type="submit" name="button">
</form>
</html>
this does replace example.com with phpfile.php, but removes other lines of the HTML. This is what I'm left with after running the PHP script:
<html>
<form method="POST" action="phpfile.php">
</form>
</html>
I haven't been programming in PHP for long and some help would be appreciated.
First of all
Bad idea on replacing strings in files. A good way to approach this is having a php file with a variable which you could programatically define as the action file to be posted at.
Anyway
As that was not the question, I don't know what those # were supposed to mean, but in PCRE(php regex parser), here is the fixed code :
preg_replace(
'/('.preg_quote($startPoint).')(.*)('.preg_quote($endPoint).')/i',
'$1'.$newText.'$3',
$file
)

How to save string entered in HTML form to text file

I have a very basic PHP file. i want to have two textboxes for user input, and a submit button. The user will enter their first and last name, then i would like to append or create a TXT file with the data entered from field1 and field2.
Possibly i am going about this the wrong way. I will post two of the ways i have been tinkering around with.
<html>
<head>
<title>Field1 & 2</title>
</head>
<body>
<form>
What is your name?<br>
<input type="text" name="field1"><br>
<input type="text" name="field2"><br>
<input type="submit" value="Submit">
</form>
<?php
$txt= $_POST['field1'].' - '.$_POST['field2'];
$var_str3 = var_export($txt, true); //is this necessary?
$var3 = "$var_str3"; //is this necessary?
file_put_contents('fields.txt', $var3.PHP_EOL, FILE_APPEND);
?>
</body>
</html>
I cant figure out how to get the data from field1 and field2 into a string variable.
I have also messed around with using this php instead of the section listed above
<?php
$txt= "data.txt";
if (isset($_POST['field1']) && isset($_POST['field2'])) {
$fh = fopen($txt, 'a');
$txt=$_POST['field1'].' - '.$_POST['field2'];
fwrite($fh,$txt); // Write information to the file
fclose($fh); // Close the file
}
?>
You should learn about HTML Forms And PHP Form Handling.
In your code you have to use a form HTTP method. And the form data must sent for processing to a PHP file.
In this code i use HTTP PSOT method you can also use GET method the result will be same. This two method is used for collecting the form data. And the php file name is "action.php".
index.html
<html>
<head>
<title>Field 1 & 2</title>
</head>
<body>
<form action="action.php" method="post">
What is your name?<br>
<input type="text" name="field1"><br>
<input type="text" name="field2"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
action.php
<?php
$path = 'data.txt';
if (isset($_POST['field1']) && isset($_POST['field2'])) {
$fh = fopen($path,"a+");
$string = $_POST['field1'].' - '.$_POST['field2'];
fwrite($fh,$string); // Write information to the file
fclose($fh); // Close the file
}
?>
Let's take a snippet from http://www.w3schools.com/html/html_forms.asp
<form action="action_page.php" method="post">
First name:<br>
<input type="text" name="firstname" value=""><br>
Last name:<br>
<input type="text" name="lastname" value=""><br><br>
<input type="submit" value="Submit">
</form>
Note the first line: upon form submission a php script is called: action_page.php.
action_page.php is your webpage with the form and the embedded php script. action_page.php both displays the empty form and then process the submitted data.
On the first line also it is specified that the submitted data is sent with the POST method.
The php part will look like this:
<?php
if( isset($_POST['firstname'] ) && isset( $_POST['lastname'] ) )
{
$txt= $_POST['firstname'].' - '.$_POST['lastname'] . PHP_EOL;
file_put_contents('fields.txt', $txt, FILE_APPEND);
}
?>
The if statement is there because the first time the script action_page.php is loaded its purpose is only to display the form and don't receive any POST data.
As the form is submitted by the user the script will receive the data and store to file.
The script will also (with this approach) display again an empty form ready for the submission of another entry.
You can rearrange things in order to have two web pages: one with just the form, another one with a "Thank you" message and the data processing php script.

Simple PHP editor of text files

I have developed a site for a client and he wants to be able to edit a small part of the main page in a backend type of solution. So as a solution, I want to add a very basic editor (domain.com/backend/editor.php) that when you visit it, it will have a textfield with the code and a save button. The code that it will edit will be set to a TXT file.
I would presume that such thing would be easy to code in PHP but google didn't assist me this time so I am hoping that there might be someone here that would point me to the right direction. Note that I have no experience in PHP programming, only HTML and basic javascript so please be thorough in any reply that you provide.
You create a HTML form to edit the text-file's content. In case it get's submitted, you update the text-file (and redirect to the form again to prevent F5/Refresh warnings):
<?php
// configuration
$url = 'http://example.com/backend/editor.php';
$file = '/path/to/txt/file';
// check if form has been submitted
if (isset($_POST['text']))
{
// save the text contents
file_put_contents($file, $_POST['text']);
// redirect to form again
header(sprintf('Location: %s', $url));
printf('Moved.', htmlspecialchars($url));
exit();
}
// read the textfile
$text = file_get_contents($file);
?>
<!-- HTML form -->
<form action="" method="post">
<textarea name="text"><?php echo htmlspecialchars($text); ?></textarea>
<input type="submit" />
<input type="reset" />
</form>
To read the file:
<?php
$file = "pages/file.txt";
if(isset($_POST))
{
$postedHTML = $_POST['html']; // You want to make this more secure!
file_put_contents($file, $postedHTML);
}
?>
<form action="" method="post">
<?php
$content = file_get_contents($file);
echo "<textarea name='html'>" . htmlspecialchars($content) . "</textarea>";
?>
<input type="submit" value="Edit page" />
</form>
You're basically looking for a similar concept to that of a contact-form or alike.
Apply the same principles from a tutorial like this one and instead of emailing using mail check out the file functions from PHP.net.
What did you Google on then? php write file gives me a few million hits.
As in the manual for fwrite():
<?php
$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fwrite($fp, '23');
fclose($fp);
// the content of 'data.txt' is now 123 and not 23!
?>
But to be honest, you should first pick up a PHP book and start trying. You have posted no single requirement, other than that you want to post a textfield (textarea I mean?) to a TXT file. This will do:
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
$handle = fopen("home.txt", 'w') or die("Can't open file for writing.");
fwrite($fh, $_POST['textfield']);
fclose($fh);
echo "Content saved.";
}
else
{
// Print the form
?>
<form method="post">
<textarea name="textfield"></textarea>
<input type="submit" />
</form>
<?php
}
Note that this exactly matches your description. It doesn't read the file when printing the form (so every time you want to edit the text, you have to start from scratch), it does not check the input for anything (do you want the user to be able to post HTML?), it has no security check (everyone can access it and alter the file), and in no way it reads the file for display on the page you want.
First thing to do is capture the information, the simplest way to do this would be the use of a HTML Form with a TEXTAREA:
<form method='post' action='save.php'>
<textarea name='myTextArea'></textarea>
<button type='submit'>Go</button>
</form>
On 'save.php' (or wherever) you can easily see the information sent from the form:
<?php
echo $_POST['myTextArea']
?>
To actually create a file, take a look at the fopen/fwrite commands in PHP, another simplistic example:
<?php
$handle = fopen("myFile.txt","w");
fwrite($handle,$_POST['myTextArea'];
fclose($handle);
?>
WARNING: This is an extremely simplistic answer! You will perhaps want to protect your form and your file, or do some different things.... All the above will do is write EXACTLY what was posted in the form to a file. If you want to specify different filenames, overwrite, append, check for bad content/spam etc then you'll need to do more work.
If you have an editor that is publicly accessible and publishes content to a web page then spam protection is a DEFINITE requirement or you will come to regret it!
If you aren't interested in learning PHP then you should think about getting a professional developer to take care of any coding work for you!
I had a similar need so we created a client-friendly solution called stringmanager.com we use on all our projects and places where CMS is not effective.
From your side, you just need to tag string in the code, i.e. from:
echo "Text he wants to edit";
to:
echo _t("S_Texthewantstoedit");
stringmanager.com takes care about the rest. Your client can manage that particular text area in our online application and sync wherever he wants. Almost forgot to mention, it is completely free.
Can use this line of code :
<form action="" method="post">
<textarea id="test" name="test" style="width:100%; height:50%;"><? echo "$test"; ?></textarea>
<input type="submit" value="submit">
</form>
<?php
$file = "127.0.0.1/test.html";
$test = file_get_contents('1.jpg', 'a');
if (isset($_POST['test'])) {
file_put_contents($file, $_POST["test"]);
};
?>
<form action="" method="post">
<textarea id="test" name="test" style="width:100%; height:50%;"><? echo "$test"; ?></textarea>
<input type="submit" value="submit">
</form>
Haven't had time to finish it, simplest possible, will add more if wanted.

Beginner Help: Creating and Storing Text Using PHP

I'm trying to write a program where the basic idea is I ask the user for input in a textarea, and then the text gets stored into a word file. Here is the code I'm trying to use:
<html>
<head>
<title>Simple Guestbook</title>
</head>
<body>
<h1>Simple Guestbook Comment Creator</h1>
<br>
<form method = "post"
action = "mysite.php">
<textarea name = "text"
rows = "10"
cols = "20">Write Here</textarea>
<input type = "submit"
value = "Submit Comment">
</form>
<?
if($_POST['text'] !== NULL){
$comment = $_POST['text'];
$file = fopen("texttest.txt", "a");
fputs($file, "<br>\n$comment");
fclose($file);
}
?>
</body>
</html>
I can't seem to get this to work properly. I was also thinking about somehow making the form action store the text and then reload the site, but I haven't gotten that to work (the original file is mysite.php, so the action is to just reload the page).
If anyone has any better ideas of an algorithm to use/different syntax to use, please let me know, as I just started learning basic PHP syntax.
Thanks
Check the following:
Does php have the permission to write files in that directory?
Is that php file called "myfile.php"?
Anyway, when something does not work and you want to know what's causing the arror, place error_reporting(-1); at the beginning of your php - it will output any error or warning, including the ones trown by fopen().
Also, you might want to check whether the variable has been correctly submitted: echo $comment right after you assign it.
Something like this might work.
You might want to do more with the values they are entering and all, but this will basically do what you are asking.
You will also want to make sure that you have the correct path of the file you are trying to write to and that that file has the correct permissions to allow it to be written to:
<html>
<head>
<title>Simple Guestbook</title>
</head>
<body>
<h1>Simple Guestbook Comment Creator</h1><br>
<?php
if (isset($_POST['submit'])) {
if (strlen(trim($_POST['comment']))) {
$file = fopen("texttest.txt", "a");
fputs($file, "$_POST['comment'])\n");
fclose($file);
}
} else {
?>
<form method = "post" action = "<?php echo($_SERVER['PHP_SELF']); ?>">
<label>Leave your comment
<textarea name="comment" rows="10" cols="20"></textarea>
</label>
<input type="submit" name="submit" value="Submit Comment" />
</form>
<?php
}
?>
</body>
Also, since you are returning to the same page you may want to put some kind of message letting the person know that they succeeded in entering something into your address book.

Categories