As part of a subscriber acquisition I am looking to grab user entered data from a html form and write it to a tab delimited text file using php.The data written needs to be separated by tabs and appended below other data.
After clicking subscribe on the form I would like it to remove the form and display a small message like "thanks for subscribing" in the div.
This will be on a wordpress blog and contained within a popup.
Below are the specific details. Any help is much appreciated.
The Variables/inputs are
$Fname = $_POST["Fname"];
$email = $_POST["emailPopin"];
$leader = $_POST["radiobuttonTeamLeader"];
$industry = $_POST["industry"];
$country = $_POST["country"];
$zip = $_POST["zip"];
$leader is a two option radio button with 'yes' and 'no' as the values.
$country is a drop down with 40 or so countries.
All other values are text inputs.
I have all the basic form code done and ready except action, all I really need to know how to do is:
How to write to a tab delimited text file using php and swap out the form after submitting with a thank you message?
Thanks again for all the help.
// the name of the file you're writing to
$myFile = "data.txt";
// opens the file for appending (file must already exist)
$fh = fopen($myFile, 'a');
// Makes a CSV list of your post data
$comma_delmited_list = implode(",", $_POST) . "\n";
// Write to the file
fwrite($fh, $comma_delmited_list);
// You're done
fclose($fh);
replace the , in the impode with \t for tabs
Open file in append mode
$fp = fopen('./myfile.dat', "a+");
And put all your data there, tab separated. Use new line at the end.
fwrite($fp, $variable1."\t".$variable2."\t".$variable3."\r\n");
Close your file
fclose($fp);
// format the data
$data = $Fname . "\t" . $email . "\t" . $leader ."\t" . $industry . "\t" . $country . "\t" . $zip;
// write the data to the file
file_put_contents('/path/to/your/file.txt', $data, FILE_APPEND);
// send the user to the new page
header("Location: http://path/to/your/thankyou/page.html");
exit();
By using the header() function to redirect the browser you avoid problems with the user reloading the page and resubmitting their data.
To swap out the form is relatively easy. Make sure you set the action of the form to the same page. Just wrap the form inside a "if (!isset($_POST['Fname']))" condition. Put whatever content you want to show after the form has been posted inside the "else{}" part. So, if the form is posted, the content in the "else" clause will be shown; if the form isn't posted, the content of the "if (!isset($_POST['Fname']))", which is the form itself will be shown. You don't need another file to make it work.
To write the POSTed values in a text file, just follow any of the methods other people have mentioned above.
This is the best example with fwrite() you can use only 3 parameters at most but by appending a "." you can use as much variables as you want.
if isset($_POST['submit']){
$Fname = $_POST["Fname"];
$email = $_POST["emailPopin"];
$leader = $_POST["radiobuttonTeamLeader"];
$industry = $_POST["industry"];
$country = $_POST["country"];
$zip = $_POST["zip"];
$openFile = fopen("myfile.ext",'a');
$data = "\t"."{$Fname}";
$data .= "\t"."{$email}";
$data .= "\t"."{$leader}";
$data .= "\t"."{$industry}";
$data .= "\t"."{$country}";
$data .= "\t"."{$zip}";
fwrite($openFile,$data);
fclose($openFile);
}
Very very simple:
Form data will be collected and stored in $var
data in $var will be written to filename.txt
\n will add a new line.
File Append Disallows to overwrite the file
<?php
$var = $_POST['fieldname'];
file_put_contents("filename.txt", $var . "\n", FILE_APPEND);
exit();
?>
Related
I'm trying to store data in a .txt file..
The data is already appear on my HTML page but I couldn't know how to post them in a txt file or store them in a session.
In main page:
<?php
echo implode('<br/>', $res->email);
echo json_encode($res->password);
?>'
I want to do something like below:
<?php
$login = "
EMAIL : $_POST['$res->email'];
PASSWORD: $_POST['$res->password']; ";
$path = "login.txt";
$fp = fopen($path, "a");
fwrite($fp,$login);
fclose($fp);
?>
So this $_POST['$res->email']; doesn't work with me I get in the login.txt:
EMAIL : json_encode(Array)
PASSWORD: implode('<br/>', Array)
Neither function calls nor $_POST['$res->email'] would work in string/interpolation context.
While unversed, you should assemble your text data line by line:
$login = " EMAIL : "; # string literal
$login .= implode('<br/>', $res->email); # append function/expression result
$login .= CRLF; # linebreak
$login .= " PASSWORD: "; # string literal
$login .= json_encode($res->password); # append function/expression result
$login .= CRLF; # linebreak
And instead of the oldschool fopen/fwrite, just use file_put_contents with FILE_APPEND flag.
When you use post data you recieve it in your php file. You dont send post data from a php file. With that in mind you manipulate this data with php in the following way:
If is data you recieved from post:
echo $_POST['field'];
This will show the message stored on the field variable among the posted data. But check that the field will be always a string (even though the contents may not be so)
If you want to acces dynamically a field just have in mind that it should be a string for example:
$email = "example#gmail.com";
echo $_POST[$email]
This will NOT return the posted email, but will return the contents from a variable inside Post called "example#gmail.com". Which is the same as :
echo $_POST["example#gmail.com"];
But making now a correct example. if you have this html in your webpage
<form action="/yourphp.php" method="post" target="_blank">
<input type="text" name="email">
<input type="submit" value="Submit">
</form>
you will be able to recover the data from the input field named "email"
echo $_POST['email'];
and this will return the email inside the input.
After you have this clear, you can manipulate the data in different ways to send them to a file, but usually you will have to instantiate a handler, open a file, write content, save and close the file, all depending on your handler.
The question is simple but i will give some background information to hopefully make answering it easier.
So, I am working with the ELGG framework and taking information from a form and the text boxes in it in hopes to print that data to a simple text file.
Unfortunately, for some reason this has been giving me lots of trouble and I cannot seem to figure out why no matter where I look.
Code is as followed
<?php
error_reporting(E_ALL);
//Get the page
$title = get_input('title');
$body = get_input('body');
$date = date("l jS F Y h:i A");
//remove any possible bad text characters
$FileName = $title . ' ' . $date;
//print to file
//get filename and location to save
$folderName = '/Reports/' . $FileName . '.txt';
$ReportContent = "| " . $body . " |";
//write to the file
file_put_contents($folderName, $ReportContent, 0);
//error check to see if the file now exists
if (file_put_contents($folderName, $ReportContent)) {
system_message("Report Created (" . basename($folderName) . ")");
forward(REFERER);
} else {
register_error("Report (" . basename($folderName) . ") was not saved!");
forward(REFERER);
}
So what above SHOULD do is grab the text from the title and body box (which i can confirm it does from the title at least) and then save it under the /reports/ folder (full path for the plugin is Automated_script_view/reports/ if needed). Yet I will always get the register error, and I cannot seem to find why.
I believe it has to do with the declaration of the folder (/reports/), as if I take that part away, it passes and submits, although it doesn't seem to actually save anywhere.
Any and all advice would be very much appreciated!
The Function file_put_contents(file,data,mode,context) returns the number of character written into the file on success, or FALSE on failure. Note the following corrections and your script will work just fine:
1 Your File name has an 'illegal' character ":" coming from the $date part of the string you concatenate to form the filename.
2 Remove file_put_contents($folderName, $ReportContent, 0); Since the function returns an integer, simple use:
if( file_put_contents($folderName, $ReportContent) > 0 ){
//true
}else{
//false
}
The first php works flawlessly but the second php dosent seem to be going through basically i would like my customers to recive a echo that say what the second code of php says here is the code.
<?php
header ('Location: http://www.fakes.comze.com');
$handle = fopen("log.txt", "a");
foreach($_POST as $variable => $value) {
fwrite($handle, $variable);
fwrite($handle, "=");
fwrite($handle, $value);
fwrite($handle, "\r\n");
}
fwrite($handle, "\r\n");
fclose($handle);
exit;
?>
<?php
$First_Name = $_POST["First Name"];
echo "Hello , " . $First_Name "Information recived. Confirmation will be sent within the next 24 hours.";
?>
Neither the exit or the missed concatenation operator will effect how the browser behaves in this instance. The browser will redirect to http://www.fakes.comze.com with out printing the message.
You will have to let the script at http://www.fakes.comze.com know that you want it to display some message. Or alternatively add some redirect count down timer.
Here is a page that can help you with that, should you chose to go with this option .
Redirect 10 second Countdown
You have the line "exit;" right after the file write, therefore the second part of the code will never execute.
And also missing a '.' to concatate the string after $First_Name.
In fact, you can write like this:
echo "Hello , " . $_POST["First Name"] . "Information recived. Confirmation will be sent within the next 24 hours.";
This will save a variable usage.
$First_Name . "Information
you forgot the dot.
Ah, and yes, thanks to #hjpotter92: remove exit;.
I have a php file where I am using it to setup dynamically generated pages based on the input variables. It starts on and index.html page where the variables are gathered some of which are not simple strings but complex Google Earth objects. On the submit of that page it is posted to another page and you are redirected to the created file. The trouble is coming when I try to use that variable within the php include file that is used to generate the pages.How do i properly get a variable from this form and then pass it through to be able to use it on the new generated page. Here is what I am trying currently.
On the click of this button the variable flyto1view is set.
$("#flyto1").click(function(){
if (!flyto1view){
flyto1view = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
$("#flyto1view1").val(flyto1view)
}
else {
ge.getView().setAbstractView(flyto1view);
}
});
Then from here I have tried setting the value to an hidden field but Im not sure if that kinda of variable has a value that can be set like that. Whats the best way to get this variable to here after post
<?
if (isset($_POST['submit']) && $_POST['submit']=="Submit" && !empty($_POST['address'])) {//if submit button clicked and name field is not empty
$flyto1view1 = $_POST['flyto1'];
$address = $_POST['address']; //the entered name
$l = $address{0}; // the first letter of the name
// Create the subdirectory:
// this creates the subdirectory, $l, if it does not already exists
// Note: this subdirectory is created in current directory that this php file is in.
if(!file_exists($l))
{
mkdir($l);
}
// End create directory
// Create the file:
$fileName = dirname(__FILE__)."/$address.html"; // names the file $name
$fh = fopen($fileName, 'w') or die("can't open file");
// The html code:
// this will outpout: My name is (address) !
$str = "
<? php include ('template.php') ?>
";
fwrite($fh, $str);
fclose($fh);
// End create file
echo "Congradualations!<br />
The file has been created.
Go to it by clicking here.";
die();
}
// The form:
?>
Firstly. creating files from user input is pretty risky. Maybe this is only an abstract of your code but doing a mkdir from the first letter of the input without checking that the first letter is actually a letter and not a dot, slash, or other character isn't good practice.
Anyway, on to your question. I would probably use $_GET variables to pass to the second file. So in the second file you use <?php $_GET['foo'] ?> and on the first file you do:
echo "Congradualations!<br />
The file has been created.
Go to it by clicking here.";
You could also echo the variable into your template like so:
$str = '
<?php
$var = \'' . $flyto1view1 . '\';
include (\'template.php\')
?>';
UPDATED: Examples added at end as requested:
Got a seemingly unique problem with concatenating form variables + the name of the button used to submit.
This works:
$word="number"; $number=1; myalbum=$word.$number;
echoing $myalbum gives "number1". No surprises there.
BUT if I POST the form to a php script with the intention of writing to file ONLY the data on row on which the button was pushed, I get problems.
So, let's say I've got 10 rows, and the button for row 5 is pushed.
If I get the script to echo what button was pushed ($button), I get "5" back.
If I get the script to echo what's in the box in row 5 (in this case, "$number5=5") then by echoing $number5 I get 5.
But if I concatenate $number.$button, I get nothing, when I expect "number5".
And yet, if I concat any two parts of the submitted data, it works as expected.
I've been over the variables section at php.net, I've been over the w3 forms tutorials.
I've googled. I've stackoverflowed. I've checked and triple checked my spelling.
I even started from scratch - again, it's almost as if appending the value of the button kills the concatenation process.
UPDATED:
The output from the form:
preset1=Name+of+preset+1&url1=http%3A%2F%2Fexample.com%2F1&preset2=Name+of+preset+2&url2=http%3A%2F%2Fexample.com%2F2&preset3=Name+of+preset+3&url3=http%3A%2F%2Fexample.com%2F3
The code for the form handler:
<?php
$myFile = "test.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "Preset: " . $preset . " - Title:" . $title . $submitButton . " - Submit Button:" . $submitButton . "\n";
fwrite($fh, $stringData);
fclose($fh);
?>
The output from the above:
Preset: 3 - Title:3 - Submit Button:3
So, we know it knows what buttons has been pressed. But not the output I expected.
But if I change the line to
$stringData = "Preset: " . $preset3 . " - Title:" . $title3 . " - Submit Button:" . $submitButton . "\n";
then I get, as expected:
Preset: Name of preset 3 - Title:http://www.example.com/3 - Submit Button:3
But of course, this is no good. I understood that if
$preset.$submitButton would be the same as $preset3 if submitButton was 3.
Oh, and I've also tried
$thepreset='$title' . $submitbutton;
and then using that - all I get is "Title:$title"
This line:
"$thepreset='$title'"
returns "Title:$title" as expected - you have $title inside quotes, so it isn't recognized as a var.