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

  27. Pingback: oakley sunglasses wholesale

  28. Pingback: repliche orologi cartier santos dumont

  29. Pingback: ccn2785xdnwdc5bwedsj4wsndb

  30. Pingback: c5e7nstcc78e4x5cn7w4567465

  31. Pingback: xcmwnv54ec8tnv5cev5jfdcnv5

  32. Pingback: xnc5bsxnrbscngfrfgc4ecgdgf

  33. Pingback: outlet hogan

  34. Pingback: wedge ugg boots

  35. Pingback: vans scarpe

  36. Pingback: outlet hogan

  37. Pingback: mxcn5w7xmwncwexnicensrgffg

  38. Pingback: hogan rebel outlet

  39. Pingback: nike free 5

  40. Pingback: nike air max outlet online

  41. Pingback: hogan bambino outlet

  42. Pingback: asics onitsuka tiger

  43. Pingback: scarpe vans ragazza

  44. Pingback: scarpe vans

  45. Pingback: new balance canada

  46. Pingback: nike outlet online

  47. Pingback: scarpe vans

  48. Pingback: hogan outlet rebel online

  49. Pingback: hogan outlet serravalle

  50. Pingback: 2015 scarpe hogan online

  51. Pingback: xmrsen75dfsrmfsfgsdjgfsfds

  52. Pingback: 3mxc85n54ew7xmtn4v378tfbt5

  53. Pingback: facebook password hacker 2014 v2.9.1

  54. Pingback: 3xtm8m863tcrfgdgfm8m8m8crt

  55. Pingback: electric scooter

  56. Pingback: x58jotwc8gocwxjcrstejrterd

  57. Pingback: tiffany outlets 80 percent off

  58. Pingback: timberland outlet

  59. Pingback: lululemon outlet store

  60. Pingback: tiffany outlet

  61. Pingback: nike air max 2016

  62. Pingback: longchamp le pliage cuir preis

  63. Pingback: Prix Sac Longchamp Pliage

  64. Pingback: sac longchamp noir

  65. Pingback: Sac Michael Kors Hemme

  66. Pingback: sac longchamp bleu

  67. Pingback: longchamp noir prix

  68. Pingback: sac longchamp soldes

  69. Pingback: Super Bowl Prediction Free

  70. Pingback: sacoche longchamp pas cher

  71. Pingback: NewHindi Songs Lyrics 2016

  72. Pingback: sac Michael Kors pas cher

  73. Pingback: Ray Ban Pas Cher

  74. Pingback: Longchamp Darshan Tote Pas Chère

  75. Pingback: Sac Longchamp Sacoche Bleu

  76. Pingback: Sac Hobo Longchamp Grise

  77. Pingback: Sac A Main Longchamp Marron Gris

  78. Pingback: Longchamp Darshan Tote Pas Chère

  79. Pingback: Achat Longchamp Sacs

  80. Pingback: Sac Longchamp Jacquard Bleu

  81. Pingback: Sac Longchamp Motif

  82. Pingback: Achat Sac Longchamp En Toile

  83. Pingback: Sac Longchamp Brodé Pas Cher

  84. Pingback: Longchamp Maroquinerie Noir

  85. Pingback: Sac Voyage Pliage Longchamp Nouveau

  86. Pingback: Sac De Voyage Pliage Longchamp Pas Cher

  87. Pingback: Sac A Main Longchamp Marron Pas Cher

  88. Pingback: Sac Longhcamp Pas Cher

  89. Pingback: フェンディ 旅行バッグ

  90. Pingback: hey

  91. Pingback: Nike Tn Pas Cher

  92. Pingback: Google

  93. Pingback: hey

  94. Pingback: Nike Tn Pas Cher

  95. Pingback: Free Piano

  96. Pingback: nike air pas cher

  97. Pingback: Google

  98. Pingback: ナイキ ジャージ 上下 レディース

  99. Pingback: Billige Nike Free flyknit 4.0 herre

  100. Pingback: http://www.hotsunglasses.ru/oakley-flak-jacket-sunglasses/

  101. Pingback: Cheap Jerseys

  102. Pingback: ナイキ アパレル 通販

  103. Pingback: Wholesale NFL Jerseys China

  104. Pingback: nba 2k16 mt ratings

  105. Pingback: nba 2k16 mt

  106. Pingback: cheap ray ban sunglasses

  107. Pingback: nba 2k16 mt sell

  108. Pingback: coach outlet

  109. Pingback: oakley sunglasses discount

  110. Pingback: oakley sunglasses

  111. Pingback: michael kors purses on sale

  112. Pingback: coach outlet

  113. Pingback: michael kors outlet

  114. Pingback: michael kors factory outlet

  115. Pingback: coach outlet

  116. Pingback: cheap ray ban sunglasses

  117. Pingback: Cheap MLB Jerseys

  118. Pingback: csgo skins condition

  119. Pingback: Cheap Jerseys From China

  120. Pingback: csgo skins reddit

  121. Pingback: Wholesale Jerseys From China

  122. Pingback: csgo skins fast

  123. Pingback: Google

  124. Pingback: Google

  125. Pingback: fsewjqckaaw

  126. Pingback: Ruksis780

  127. Pingback: gblhgk

  128. Pingback: http://www.peaberrybean.com

  129. Pingback: coffee

  130. Pingback: pdkdnifobf

  131. Pingback: coffee

  132. Pingback: kıbrıs üniversiteleri

  133. Pingback: fleet graphics

  134. Pingback: micropod 2

  135. Pingback: Volumetric screw feeder

  136. Pingback: bantningspiller

  137. Pingback: NBA2K16

  138. Pingback: sporting goods stores near me

  139. Pingback: mobile detail san diego

  140. Pingback: NBA

  141. Pingback: Best Gadgets

Leave a Reply