I have made a script with a form which is supposed to submit a persons email to a .txt file, only problem is that nothing happends to the .txt file, it is kept blank when the function is called. Both the html file and the php file is kept in the same folder and the .txt file is named formdata.txt .
Html code:
<form name="newsletter-form" action="process-form-data.php" method="post" id="newsletter-form">
<input type="email" name="newsletter-email" id="newsletter-email" class="form-control" placeholder="Enter Your Email" data-validate="validate(required, email)" />
<input type="submit" id="newsletter-submit" class="btn" value="Notify Me" />
</form>
Php code named process-form-data.php:
<?php
// Receive form Post data and Saving it in variables
$email = $_POST['newsletter-email'];
// Write the name of text file where data will be store
$filename = "formdata.txt";
// Marge all the variables with text in a single variable.
$f_data= '
Email : '.$email.'
=========================
';
echo 'Form data has been saved to '.$filename.' <br>
Click here to read ';
$file = fopen($filename, "a");
fwrite($file,$f_data);
fclose($file);
?>
Your code works for me.
Here's a variation using file_put_contents:
// Receive form Post data and Saving it in variables
$email = $_POST['newsletter-email'];
//$email = 'myhappymail#unhappy.com';
// Write the name of text file where data will be store
$filename = "formdata.txt";
// Marge all the variables with text in a single variable.
$f_data= '
Email2! : '.$email.'
=========================
';
file_put_contents( $filename, $f_data, FILE_APPEND | LOCK_EX );
// $file = fopen($filename, "a");
// fwrite($file,$f_data);
// fclose($file);
echo 'Form data has been saved to '.$filename.' <br>
Click here to read ';
Do a:
var_dump( $_POST );
die;
at the top of your script. I'm thinking you're missing your POST data.
Related
I'm trying to make a scrolling text box in a page "front-end page" read from text file "msg.txt"
<div class="scroll-slow">
<?php echo file_get_contents('../msg.txt'); ?>
</div>
I added this code to add textbox and save button in my backend:
<html>
<head>
<title></title>
</head>
<body>
<form action="msg.txt" method="POST">
<input name="field1" type="text" />
<input type="submit" name="submit" value="Save">
</form>
</body>
</html>
<?php
if(isset($_POST['field1'])) {
$data = $_POST['field1'] . "\n";
$ret = file_put_contents('../msg.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
} else {
echo "$ret bytes written to file";
}
} else {
die('no post data to process');
}?>
Also I included txt file called "msg.txt" in my root, to make the save button save the text into the file then the scrolling msg box will read the file
My problem is:
The scrolling textbox doesn't read from the file
The save button doesn't save into the file it's just open the file!
What I'm doing wrong?
I'm sorry I know it's a mess, but I'm trying to learn.
You have to make action tag blank to execute the PHP code which is inside if statement
Change
action="msg.txt"
to
action=""
If you are doing coding on PH, you should use php file in action tag, you can not perform any action on txt file.
To append the text every time to existing file use
$txt = "This is text";
$myfile = file_put_contents('text_file.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);
Here you can use jquery and ajax for get activ value of text
$.ajax({
url: "backendFile.php",
type: "post",
data: {
text: $("input[name='field1']").val()
},
success: (e) => {
$(".scroll-slow").html(e)
}
}
Your backendFile.php
<?php
if(isset($_POST['field1'])) {
$data = $_POST['field1'] . "\n";
$ret = file_put_contents('../msg.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
} else {
echo "$ret bytes written to file\n".file_get_contents("../msg.txt");
}
} else {
die('no post data to process');
}
?>
You are submitting the form data to a text file, text files won't be able to handle form data.
You need to send data to php file, in your case just removing the action from form tag would work.
Is it possible to save input data in php file without using any database?
Something like:
echo " inputted text.. ";
or
$text = "Text..";
Use fwrite, very easy :
<?php
$fp = fopen('myfile.txt', 'w');
fwrite($fp, 'this is my database without database :p ');
fclose($fp);
?>
If you want to work with a form, and extract some variables into a file you can use:
Your Form in form.html
<form action="recipient.php" method="POST">
INPUT1: <input type="text" name="text1" id="input1"><br/>
INPUT2: <input type="text" name="text2" id="input2"><br/>
FILENAME: <input type="text" name="filename" id="filename">
<button type="submit">Send now</button>
</form>
Your PHP recipient.php - without any validation checks:
<?php
$varA = "\$varA = ".$_POST['input1'].";"; // put your string into varible $varA
$varB = "\$varB = ".$_POST['input1'].";"; // put your string into varible $varA
$fileName = $_POST['filename']; // set a filename from form field
$text = $varA ." ". $varB; // add all together
$filepath = fopen('/var/www/html/'.$fileName.'.php', 'w+'); // set filepath and fopen to new PHP-file
fwrite($filepath, '<?php '. $text); // write text as PHP-file
fclose($filepath); // close file
?>
If you haven't read about them yet check HTML-Forms.
You might also want to look into arrays and serialisation.
But apart from that I highly recommend to have a look into Databases (PDO) - it safes you time and is much more secure.
Here's my code:
The PHP Code
<?php
if(isset($_POST['Submit'])){
$title ='myPost.php';
echo $title;
//the data
$data = "Hey I am Aidan\n";
//open the file and choose the mode
$fh = fopen($title, "a");
fwrite($fh, $data);
//close the file
fclose($fh);
}
?>
The HTML Form Code
<form action="<?php echo $title; ?>" method="post">
<input type="submit" name="Submit" value="submit">
</form>
When form is submitted I want to load that newly created file on the next page.
use this is php to move to next page . header('Location: /somewhere');
write this code in php tags of which you displayed in html and in place of somewhere you have to write the name of your file.php ... also write this code in first line of your php document inside php tags ob_start();
After you close the file, redirect the user to it:
//close the file
fclose($fh);
// eg: /path/to/page.php. Also try $_SERVER['PHP_SELF']
$currentPath = $_SERVER['SCRIPT_NAME'];
// replace the old filename with $title
$newPath = preg_replace('#(.*/)[^/]*#','$1' . $title, $currentPath);
// Redirect browser to new file and stop.
header("Location: $newPath");
exit;
I am fairly new to PHP and am having trouble with an assignment. The assignment is to create a simple address book in PHP, and i would like my address book to display all addresses that are in it along with a submission box at the bottom to add more addresses. Currently, I can get the addresses to display, but the submission box gives me an error ") Notice: Undefined variable: addres_add in C:\wamp64\www\address_tmp\address.php on line 18"
This is my code thus far, I snagged the submission box code from another answer here on StackOverflow, but I don't know how to modify it to fit my needs.
<?php
//Open address book file and print to user
$fh = fopen("address_book.txt", "r+");
echo file_get_contents("address_book.txt");
//Perfom submit function
if(isset($_POST['Submit']))
fseek($fh, 0, SEEK_END);
fwrite($fh, "$addres_add") or die("Could not write to file");
fclose($fh);
print("Address added successfully. Updated book:<br /><br />");
echo file_get_contents("address_book.txt");
{
$var = $_POST['any_name'];
}
?>
<?php
//HTML for submission box?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="text" name="any_name">
<input type="submit" name="submit">
</form>
<p>
You never assigned the variable from the form input. You need:
$addres_add = $_POST['any_name'];
fwrite($fh, "$addres_add") or die("Could not write to file");
Also, if you're just adding to the file, you should open it in "a" mode, not "r+". Then you don't need to seek to the end, that happens automatically.
You probably should put a newline between each record of the file, so it should be:
fwrite($fh, "$addres_add\n") or die("Could not write to file");
Otherwise, all the addresses will be on the same line.
Here is a simpler version of your program.
<?php
$file_path ="address_book.txt";
// Extract the file contents as a string
$file_contents = file_get_contents($file_path);
if ($file_contents) // Check if the file opened correctly
echo($file_contents . " \n"); // Echo contents (added newline for readability)
else
echo("Error opening file. \n");
// Make sure both form fields are set
if(isset($_POST['submit']) && isset($_POST['any_name']))
{
// Append the new name (used the newline character to make it more readable)
$file_contents .= $_POST["any_name"] ."\n";
// Write the new content string to the file
file_put_contents($file_path, $file_contents);
print("Address added successfully. Updated book:<br /><br />");
echo($file_contents);
}
else
{
echo("Both form elements must be set. \n");
}
?>
//HTML for submission box?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="text" name="any_name">
<input type="submit" name="submit">
</form>
Even with no comments it should be self explanatory. I leave the proper error dealing to you.
To answer your question, the error was being caused because the $address_add variable wasn't previously declared. You also added quotes to it, making it a string.
How to make a textbox form redeem a promo code form a text file in php i cant seem to figure it out it's for my csgo gambling site i want them redeem to redeem codes that comes from a text file /promo/codes.txt and make it so they can just use any codes from the list in the text file but im to useless :(
It depends totally on the format of the file.
Example:
ZQC01
ZQR92
ZQA84
ZQD73
To check if a promotion code is in this file and remove it afterwards:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$myPromoCode = isset($_POST['promocode']) ? $_POST['promocode'] : false;
$contents = file_get_contents('/path/to/file.txt');
$promoCodes = explode("\n", $contents);
// Check if the promo code is present in the file
if ($myPromoCode && in_array($myPromoCode, $promoCodes)) {
// Find the corresponding key
$key = array_search($myPromoCode, $promoCodes);
// Remove the code
unset($promoCodes[$key]);
// Write coes back to file
$contents = implode("\n", $promoCodes);
file_put_contents('/path/to/file.txt', $contents);
} else {
die("Promotion code doesn't exist");
}
}
?>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
<input type="text" name="promocode" />
<button type="submit">Redeem</button>
</form>