How to save string entered in HTML form to text file - php

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.

Related

How to acess form details in php page using html 'id' attribute

i have a form having employeeNo,name and a submit button. when the form is submitted it redirects to a php page, Now the problem is i want to access the values of the form by using 'id' attribute?if possible i need the html and php code.
Is there a way to solve this Problem?
enter code here<html>
<head>
</head>
<body>
<form action="test.php" method="">
<input type="text" name='employeeNo' id="input1">
<br>
<input type="text" name='name' id="input2">
<br>
<input type="submit" id="input3">
</form>
</body></html>
In your test.php file you need to retrieve the values. Since you don't define any method in your form, by default it should be "GET"
Your php file could look like the following:
<?php
$employee_no = $_GET['employeeNo'];
$name = $_GET['name'];
I would suggest defining your form method as POST though, like the following:
...
<form action="test.php" method="POST">
...
so your php file will retrieve values from form like this:
<?php
$employee_no = $_POST['employeeNo'];
$name = $_POST['name'];
You may also look at this for further explanation:
https://www.w3schools.com/php/php_forms.asp

After submit redirect to another page not with PHP

I have couple of identical HTML pages which take user input and with PHP I save the input on text files. As it's always the same I would like to apply the same PHP on every html page. So my question is if there is a way to redirect to the next html page but not through PHP, so that the PHP can be reusable for all the pages?
Because if I add onclick="window.location.href='/main2.html' then the PHP is not fired up or if I change action="main2.html" then again the PHP is not included. Or if I add header("Location: main2.html"); then it cannot really be applied to all the html pages, as it goes main.html -> main2.html -> main3.html etc.
HTML 1:
<form method="post" action="process.php">
<input type="text" name="address" required>
<input type="submit" value="Submit" id="intro">
</form>
HTML 2:
<form method="post" action="process.php">
<input type="text" name="address" required>
<input type="submit" value="Submit" >
</form>
PHP:
<?php
$myfile = fopen("text.txt", "a+");
$address = $_POST['address'].";";
fwrite($myfile, $address);
//header("Location: main2.html");
fclose($myfile);
?>
Thank you in advance!
Although you don't want to use PHP, it can make this pretty simple for you. You can use the session variable in PHP to track the user, the entries he has made and even allow them to go back and forward.
You can read more on it here.
You can redirect the user based on the session counter or the source from where the call is made and direct them accordingly to the next page. This makes your code scalable as well.
So you code will be something like this:
session_start();
if( isset( $_SESSION['counter'] ) ) {
$_SESSION['counter'] += 1;
}else {
$_SESSION['counter'] = 1;
}
$newURL = "HTMLPage".$_SESSION['counter']."html";
header('Location: '.$newURL);
The above code will redirect the user to the next page. PS: You will have to handle the case for your last html page.

Saving data from HTML form on server?

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

Why am I getting this PHP error?

So here's my full code
<!DOCTYPE html>
<html>
<body>
<h1>Encrypt</h1>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Enter word to encrypt<input type="text" name="in">
<input type="submit">
<hr>
</form>
<h1>Decrypt</h1>
<form>
Enter word to decrypt<input type="text" name="out">
<input type="submit">
<hr>
</form>
</body>
</html>
<?php
$encrypt = $_POST['in'];
?>
And here's the error I get
Notice: Undefined index: in in /Users/idrisk/Colourity/si/index.php on line 20
Line 20 is $encrypt = $_POST['in']; and I don't see what I'm doing wrong with it. Any ideas?
As a general practice for forms in php, always check if the submit button has been clicked.
First name your submit button:
<input type="submit" name="submit">
then further in your php:
if (isset($_POST['submit'])) {
// do your stuff, eg...
$encrypt = $_POST['in'];
}
EDIT #1: Added to that, you seem to have 2 forms and 2 submit buttons. I suggest you keep only one form, and one submit button (remove the 2nd form element and submit button).
If you really need 2 forms, name your submit buttons differently and then you can call them separately.
<input type="submit" name="submit-in">
<!-- ... -->
<input type="submit" name="submit-out">
<?php // ...
if (isset($_POST['submit-in'])) {
// do your stuff, eg...
$encrypt = $_POST['in'];
}
if (isset($_POST['submit-out'])) {
// do your stuff, eg...
$dencrypt = $_POST['out'];
}
EDIT #2: If you want to echo stuff posted in your form, make sure you do the form submission checking and variable setting before the form and then echo the variable after the form (or wherever you want).
you need to first check if the form has been sent, if it hasn't then $_POST['in'] does not yet exist thus throwing the error
May be nothing but you called a php script after closing the form /form, the body /body and then then the HTML /html
replace this code $encrypt = $_POST['in']; by this $encrypt = #$_POST['in'];
this is an error on client server when you upload this file on remote server you will not saw this. use # sign on the client server when you saw this error in future.

PHP form - on submit stay on same page

I have a PHP form that is located on file contact.html.
The form is processed from file processForm.php.
When a user fills out the form and clicks on submit,
processForm.php sends the email and direct the user to - processForm.php
with a message on that page "Success! Your message has been sent."
I do not know much about PHP, but I know that the action that is calling for this is:
// Die with a success message
die("<span class='success'>Success! Your message has been sent.</span>");
How can I keep the message inside the form div without redirecting to the
processForm.php page?
I can post the entire processForm.php if needed, but it is long.
In order to stay on the same page on submit you can leave action empty (action="") into the form tag, or leave it out altogether.
For the message, create a variable ($message = "Success! You entered: ".$input;") and then echo the variable at the place in the page where you want the message to appear with <?php echo $message; ?>.
Like this:
<?php
$message = "";
if(isset($_POST['SubmitButton'])){ //check if form was submitted
$input = $_POST['inputText']; //get input text
$message = "Success! You entered: ".$input;
}
?>
<html>
<body>
<form action="" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
The best way to stay on the same page is to post to the same page:
<form method="post" action="<?=$_SERVER['PHP_SELF'];?>">
There are two ways of doing it:
Submit the form to the same page: Handle the submitted form using PHP script. (This can be done by setting the form action to the current page URL.)
if(isset($_POST['submit'])) {
// Enter the code you want to execute after the form has been submitted
// Display Success or Failure message (if any)
} else {
// Display the Form and the Submit Button
}
Using AJAX Form Submission which is a little more difficult for a beginner than method #1.
You can use the # action in a form action:
<?php
if(isset($_POST['SubmitButton'])){ // Check if form was submitted
$input = $_POST['inputText']; // Get input text
$message = "Success! You entered: " . $input;
}
?>
<html>
<body>
<form action="#" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
Friend. Use this way, There will be no "Undefined variable message" and it will work fine.
<?php
if(isset($_POST['SubmitButton'])){
$price = $_POST["price"];
$qty = $_POST["qty"];
$message = $price*$qty;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="#" method="post">
<input type="number" name="price"> <br>
<input type="number" name="qty"><br>
<input type="submit" name="SubmitButton">
</form>
<?php echo "The Answer is" .$message; ?>
</body>
</html>
You have to use code similar to this:
echo "<div id='divwithform'>";
if(isset($_POST['submit'])) // if form was submitted (if you came here with form data)
{
echo "Success";
}
else // if form was not submitted (if you came here without form data)
{
echo "<form> ... </form>";
}
echo "</div>";
Code with if like this is typical for many pages, however this is very simplified.
Normally, you have to validate some data in first "if" (check if form fields were not empty etc).
Please visit www.thenewboston.org or phpacademy.org. There are very good PHP video tutorials, including forms.
You can see the following example for the Form action on the same page
<form action="" method="post">
<table border="1px">
<tr><td>Name: <input type="text" name="user_name" ></td></tr>
<tr><td align="right"> <input type="submit" value="submit" name="btn">
</td></tr>
</table>
</form>
<?php
if(isset($_POST['btn'])){
$name=$_POST['user_name'];
echo 'Welcome '. $name;
}
?>
simple just ignore the action attribute and use !empty (not empty) in php.
<form method="post">
<input type="name" name="name">
<input type="submit">
</form>
<?PHP
if(!empty($_POST['name']))
{
echo $_POST['name'];
}
?>
Try this... worked for me
<form action="submit.php" method="post">
<input type="text" name="input">
<input type="submit">
</form>
------ submit.php ------
<?php header("Location: ../index.php"); ?>
I know this is an old question but since it came up as the top answer on Google, it is worth an update.
You do not need to use jQuery or JavaScript to stay on the same page after form submission.
All you need to do is get PHP to return just a status code of 204 (No Content).
That tells the page to stay where it is. Of course, you will probably then want some JavaScript to empty the selected filename.
What I do is I want the page to stay after submit when there are errors...So I want the page to be reloaded :
($_SERVER["PHP_SELF"])
While I include the sript from a seperate file e.g
include_once "test.php";
I also read somewhere that
if(isset($_POST['submit']))
Is a beginners old fasion way of posting a form, and
if ($_SERVER['REQUEST_METHOD'] == 'POST')
Should be used (Not my words, read it somewhere)

Categories