Home » Programming » How to save web form data in a text file

How to save web form data in a text file

You can save your web form data in a text file instead of saving it in a MySQL table using a simple PHP script. The advantage of doing this is that you might not have the MySQL server installed on your server or you might like to save your web form data in another form.

In fact if you save your web form data in a text file as comma separated values (CSV) you can later on import your data in any file format. For instance, after downloading your text file, you can import the values in an Excel sheet, or into an Access table, or later on, even in a MySQL table. You can use it with any software the uses comma separated values.

Saving web form data in a text file with PHP

Why PHP? First of all, I’m more comfortable with PHP. Second, in order to achieve this you need some server side scripting and there is a 99.99% chance that your web host allows PHP scripts. So that’s now out of our way.

Suppose you have the following web form on your website or blog:

<form name=”web_form” id=”web_form” method=”post” action=”process-form-data.php”>
        <p><label>Enter name: </label><input type=”text” name=”name” id=”name” /></p>
        <p><label>Enter email: </label><input type=”text” name=”email” id=”email” /></p>
        <p><input type=”submit” name=”s1″ id=”s1″ value=”Submit” /></p>

Since we only need an example so we’ll have just two fields for the form, namely name and email. Next, create a text file containing this line:


and name it as, say, formdata.txt. As you can see, it has a comma between the two headers. Also press the Enter key once after writing Email just so that the end of file pointer is in the next line. Upload this file to the folder where you have your web form file and the PHP script file that will save your form data in this text file. Make sure your text file is writable on the server (the file permission should be set to 666) and you can do it by right-clicking it through your FTP client.

Now to the file where the real action happens, that is, “process-form-data.php”. This file contains the following lines of code:

$name = $_POST[‘name’];
$email = $_POST[’email’];
$fp = fopen(”formdata.txt”, “a”);
$savestring = $name . “,” . $email . “n”;
fwrite($fp, $savestring);
echo “<h1>You data has been saved in a text file!</h1>”;

The first two lines saves the web form post data in local PHP variables. The 3rd line opens the text with the appropriate permission. In PHP we can open files with difference permissions, but here, “a” means open the file in write-mode and append the new information (without overwriting the existing information. You can refer to PHP official documentation for all file opening permissions. Just remember that a wrong permission can delete your file or erase all your data.

The 4th line creates a string that combines the two values — name and email — puts a comma between them and then inserts the new line character so that the end of file pointer moves to the next line.

The fwrite function writes the newly-created line and the remaining code is very easy to understand.

If you are not saving very critical data, saving your web form data in a text file is better than saving it in a database table as then it is easier to access it without extra programming knowledge.

25 thoughts on “How to save web form data in a text file

  1. Cute_archi9

    Explanation was simply superb .. But how do u display the data stored in a text file in a php page …

  2. Robert

    In trying to apply your code, I kept getting a syntax error of unexpected “,” in line 12.  This is the delimiter between name and email.

    Any suggestions for a fix.
    Robert    harding471@aol.com

  3. torq

    Needs “n” instead of just “n” for the character return to happen. Line 4 should read like this:

    $savestring = $name . “,” . $email . “n”;

    Other than that, great tutorial! Thanks!

  4. Dan

    When opening the html file on a browser, the submit button is not displayed correctly (see image) and does not allow submission. Also, is there a quick way to include radio button or drop-down menus? Thanks for this post!

  5. Pingback: Your Questions About Average Salaries By Age - Income Distribution | Income Distribution

  6. Pingback: Use PHP to write to a file | elizaibeth

  7. Traceguy

    Haha, Thank you. I was having problems. I was using my homework from like 2 years ago for reference but It would apear I didnt do it right back them -.-, this helped me correct my old homework and my current webpage.

  8. Pingback: chella anilkumar (chellaanilkumar) | Pearltrees

  9. harold

    For those having issues with syntax errors, the data not appending, or bad variables: change all your quotes to apostrophes in the fopen() and $savestring lines. Also, n returned an error for me.

  10. Harold King

    I have a better solution.

    $fp = fopen('formdata.csv', 'a');
    fwrite($fp, $name . ',' . $email . ',' . PHP_EOL);

    fwrite() allows multiple variables and end of line declarations, so you can get rid of the $savestring variable altogether. Replace quotes with apostrophes. fopen('a') suggests we're appending to the document, and we may as well make it neat, but 'n' doesn't work as a line break; it simply outputs the text n, which doesn't return carriage in the document. Appending (.) PHP_EOL gets the carriage return done. Finally, using a .csv format instead of .txt allows you to import data into excel for future use. Make sure you set .csv file permissions to 666 as author suggests.

  11. Stonydallas

    I get this:

    Warning: fopen(�formdatatxt�) [function.fopen]: failed to open stream: Inappropriate ioctl for device in /home/dallas88/public_html/Smac/projects/fanfic/process-form-data.php on line 4

    Warning: fwrite(): supplied argument is not a valid stream resource in /home/dallas88/public_html/Smac/projects/fanfic/process-form-data.php on line 6

    Warning: fclose(): supplied argument is not a valid stream resource in /home/dallas88/public_html/Smac/projects/fanfic/process-form-data.php on line 7

    You data has been saved in a text file!

  12. Victor Dave

    I have a question, I made the pages, the script, the csv… everything works fine…. but after form submission I am taken to new page which has the echo text… instead I want to reload the page or refresh the form immediately after submission.

  13. Soundar

    I have done the above instruction. Once after I submitted the Name & Email the result page shows as “You data has been saved in a text file!” but when I open the .txt file it’s not there. Why??? & How to get the data appear there.., Please help me I dnt know anything about FTP.

  14. Lynn

    I have applied this code, but my data is not save inside the text file… Why is that so? Thanks

  15. 2015年の最新作が激安特価 2015春夏新色追加

    !私がしてきた先に行くとあなたを与えるために| 勇気勇気今、最終的に得たしながら長い時間 以下のためのあなたのウェブサイトからシャウトアウトハフマン テキサス!ちょうどしたかったあなたを伝える 偉大な良い幻想を追いつきます!
    2015年の最新作が激安特価 2015春夏新色追加 http://surveyors.nl/?199=24629

  16. Walker

    Los restos de saliva son fuentes de infección reconocidas
    por los dentistas y a las que no se les da la suficiente importancia.

  17. iniciacion masoneria

    Hello there! I know this is kinda off topic however , I’d figured I’d ask.
    Would you be interested in trading links or maybe guest authoring a blog article or vice-versa?
    My site covers a lot of the same subjects as yours
    and I believe we could greatly benefit from each
    other. If you are interested feel free to shoot me an email.
    I look forward to hearing from you! Wonderful blog by the way!

  18. Marshall

    Today, I went to the beach front with my kids. I found a sea shell and gave
    it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.”
    She placed the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear.
    She never wants to go back! LoL I know this is completely
    off topic but I had to tell someone!

    my blog post comment avoir plus de likes –

  19. IЕBCIncusy

    Everybody knows that professional translation is an important part of successful business. Accurate technical translation plays a great role in company development. If you cannot find professional translator but still need to translate English to your foreign language, Intercombase translation services is the best choice for you. We deal with wide range of English translations. We translate English to all European and Asian languages. Our language translators can provide english to arabic translation, english to chinese translation, english to danish translation, english to dutch translation, english to farsi translation, english to finnish translation, english to french translation, english to german translation, english to greek translation, english to hebrew translation, english to hindi translation, english to italian translation, english to japanese translation, english to korean translation, english to norwegian translation, english to polish translation, english to portuguese translation, english to russian translation, english to spanish translation, english to swedish translation, english to turkish translation, english to ukrainian translation. We deliver high quality technical translation, engineering translation, business translation, medical translation, IT translation, legal translation, industrial translation and many more. Our multilingual team includes highly qualified translators and certified linguists as well as technical experts from different industries. It allows your technical translation be correct and relevant. Our language translators are able to handle large volume of text translations. Moreover they guarantee that your translation will be exact, correct and done in time.
    IntercomBase.Com: english to spanish translation

  20. アルマーニ 公式 店内全品ポイント10倍

    あなたは実際それはあなたのプレゼンテーションとそう簡単に見えるように、私は、この問題を見つける| その私が思うに、私は理解できないだろうされるように本当に実際に何かを。 と非常に私のための広範なそれはあまりにもそうです。あなたの次のポストのために楽しみにして| 私は私は、私がしますそれのこつを取得しよう!
    アルマーニ 公式 店内全品ポイント10倍 http://www.resource4signs.com/gain-23660-189.html

  21. Pingback: tier2 junk

  22. Pingback: chanel tasche schwarz weiä

  23. Pingback: cartier love rose

  24. Pingback: cheap oakleys

  25. Pingback: hyperrev 2015

  26. Pingback: bague b zero1 réplique

Leave a Reply