PHP form inserts data into CSV file
By Alpho011
Today we are going to use a .csv (comma seperated values) file to store values from a online PHP web form.
A csv file is file that you can create easily with Microsoft Excel, here are the full and upgrade versions, also you can also get knowledge from this recommended book on excel for further knowledge that is beyond the scope of this tutorial.
Ok first off we will use the multi-purpose page technique from Build Database Driven Website Using PHP and MySql.
We aren't using a database, we are going to use Excel in .csv form to store the form data.
Why do this when you can use a database:
- Data is portable
- Data is readily readable by MS office
- Data is web ready
- Web hosting is simple, FTP and done.
Since my server location is offline, email me for the src code, sorry.
First we create a simple form:
<form id="form1" name="form1" method="post" action="<?=$_SERVER['PHP_SELF'];?>">
<table class="formatTblClass">
<tr>
<th colspan="6"><?=$message;?></th>
</tr>
<tr>
<td width="68"><span>First Name</span></td>
<td width="215"><input class="<?=$aClass;?>" type="text" name="fn" id="fn" /></td>
<td width="62"><span>Last Name</span></td>
<td colspan="3"><input class="<?=$aClass;?>" name="ln" type="text" id="ln" size="50" /></td>
</tr>
<tr>
<td colspan="6"><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="71">Address</td>
<td width="721"><input class="<?=$aClass;?>" name="address" type="text" id="address" size="100" /></td>
</tr>
</table></td>
</tr>
<tr>
<td><span>City</span></td>
<td><input class="<?=$aClass;?>" type="text" name="city" id="city" /></td>
<td><span>State</span></td>
<td width="148"><input class="<?=$aClass;?>" type="text" name="state" id="state" /></td>
<td width="24"><span>ZIP</span></td>
<td width="255"><input class="<?=$aClass;?>" type="text" name="zip" id="zip" /></td>
</tr>
<tr>
<td><span>Phone</span></td>
<td><input class="<?=$aClass;?>" type="text" name="phone" id="phone" /></td>
<td><span>Email</span></td>
<td><input class="<?=$aClass;?>" type="text" name="email" id="email" /></td>
<td><input name="emailMe" type="checkbox" id="emailMe" value="Yes" checked="checked" /></td>
<td>Please send me email</td>
</tr>
<tr>
<td colspan="6"><span>Comments
<textarea name="comments" id="comments" cols="45" rows="5"></textarea>
</span>
<div align="center">
<input type="submit" name="Submit" id="Submit" value="Submit" />
<input type="reset" name="Reset" id="button" value="Reset" />
</div></td>
</tr>
</table>
</form>
Same deal, simple form, great results, you can use this technique using any type of form you want, even then one from my other article.
Then we need to create a csv file;
Excel and for this particular one we created the following headers:
First Name
Last Name
Address
City
State
ZIP
Phone
Email
Yes/No
Comments
Those will go across the first row and will match our variables in our PHP script to insert them into the sheet.
After clicking the submit button we want to do some checks:
$fn = $_POST['fn'];
$ln = $_POST['ln'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$emailMe = (isset($_POST['emailMe'])) ? $_POST['emailMe'] : 'No';
$comments = $_POST['comments'];
//validate
if(empty($fn) || empty($ln) || empty($address) || empty($city) || empty($state) || empty($zip) || empty($phone) || empty($email)){//show the form
$message = 'Fill in areas in red!';
$aClass = 'errorClass';
In this case we show the form again, somebody may have miss some things we find important.
If all is good we get to the good stuff the insert:
First we tie all the data up in a variable called $csvData:
//this is where the creating of the csv takes place
$cvsData = $fn . "," . $ln . "," . $address . "," . $city . "," . $state . "," . $zip . "," . $phone . "," . $email . "," .$emailMe . "," . $comments ."\n";
then we open the file:
$fp = fopen("formTest.csv","a"); // $fp is now the file pointer to file $filename
And then we write the form contents to the file:
if($fp){
fwrite($fp,$cvsData); // Write information to the file
fclose($fp); // Close the file
And close the connection or file.
Simple, once again look over the source files and get a feel for doing this, these techniques can be used in conjuction with email, storing in db and storing this in a regular text file, the limit is your imagination.
Please be sure to leave any questions or comments you may have about this, and enjoy your projects.
Reference Materials
![]() | Amazon Price: $11.05 List Price: $21.99 |
![]() | Amazon Price: $94.99 List Price: $229.95 |
![]() | Amazon Price: $76.45 List Price: $109.95 |
![]() | Amazon Price: $12.58 List Price: $39.95 |
Comments
Thanks and I hope this proves helpful!
thank you so much! my php and scripting skills are very much copy-and-paste-and-hack-and-trial-and-error and for hours now i've been trying to find a way to do a simple club guestlist sign-up form for a friend and i've managed to hack your sample enough to make it work for this purpose.
such simple guestlist scripts are quite literally impossible to find... not on hotscripts, not anywhere. (i guess it's become most programmers can whip up something like this in 5 minutes)
once again, thanks and i'm bookmariking this for when you post something else this useful.
Well I appreciate that, and I am very pleased it worked for you!
what happens if someone enters a comma into the input field?
Well I did it and it still inserted, but the real problem will more than likely come when we present the data (loop it out).
we should check for any bad things (validate and clean).
$badThings = array(" , " );
Look through the posted values and stop the insert.
Thanks for the comments.
Hi Alpho011,
Technical things described easy. Now we can make our own CSV files.
Thanks.
Jyoti Kothari
hi.
i downloade the file and run it but it dosen't work .
when i press submit button then i got this error message:"The file /C:/New Folder (2)/<?=$_SERVER['PHP_SELF'];?> cannot be found. Please check the location and try again."
could you please help me??
Brilliant and Beautiful! So easy and an inexpensive option to filemaker pro database hosting. But easy to import into our clients FMPro datbases.
The email checkbox is not initiating an email for some reason though.
do you have a gui editor that you recommend for adding new forms or adding a header or logo? Would frontpage work?
Great Job,
Respectfully,
Jared
www.developerranch.com
Happy Easter payam :
from the look of the error "do you have PHP installed?"
The PHP_SELF should read the name of file, in other words it submits on itself.
Happy Easter jared Schott:
I always use Dreamweaver in code view but you can edit in any editor to include Notepad, straight html and php, the GUI based editors have a syntax editor which are really good in helping and syntax coloring.
And thank you for the comment.
"what happens if someone enters a comma into the input field?"
The safest way to create a CSV file is to have each value bounded by a double quote so that the data looks like this:
"field 1","field 2","field 3","etc"
There should be no space between the quotes and commas. By doing this it is safe to have commas in a field and usually safe to have new line breaks in the field as well.
Escape a double quote in the field value with another double quote i.e. ""
I would much rather save my field values into an array and then implode the data.
$csvArray = array($fn, $ln, $address, $city, $state, $zip); $csvData = '"'.implode('","', $csv_values).'"'.PHP_EOL;
This allows for easy edits. For example to reorganize the fields.
$csvArray = array($address, $city , $state, $zip, $ln, $fn); $csvData = '"'.implode('","', $csv_values).'"'.PHP_EOL;
Just my two cents.
After fill in all the information and submit, it shows "Error saving file! Fill in areas in red!". Please help
Clareen: Are the permissions on the CSV file set to 755 or 777, that is what is sounds like, you can use and FTP program to set the file settings, by right clicking on the folder and setting the read,write settings.
Hey I've been wondering what CSV means but was too lazy to Google it. Now I know. Thanks!
Thanks so much for posting this tutorial, I can't believe how easy it was to implement this script!
One (or more) question(s)... If the check fails and the form is redisplayed with the red outlines, all of the previously entered data is removed and the user must start over.
1. What maintains the user entered data between submits?
2. What would I need to look at in order to maintain this information with the script you have already provided?
Thanks again,
Jimmy
after I fill in all the fields I get the following error
The website declined to show this webpage HTTP 403 Most likely causes:This website requires you to log in.
Operating System: 2003 Standard Edition SP2Webserver: Apache 2.2.6PHP: 5.2.4
You are more than likely recieving this because the directory listings are turned off on Apache.
u create the string from input date , but in that if , is come in the address field then what happend it insert it into new cell not in same cell of address field.
Hi Alpho011,
I seem to be having problems with the permissions. after i click submit this error happens on top of the page.
Warning: fopen(formTest.csv) [function.fopen]: failed to open stream: Permission denied in C:\www\contactFrm.php on line 215
Btw. Im using IIS on windows xp pro . and php 5.29-2
thanks so much
Hi Alpho011,
I seem to be having problems with the permissions. after i click submit this error happens on top of the page.
Warning: fopen(formTest.csv) [function.fopen]: failed to open stream: Permission denied in C:\www\contactFrm.php on line 215
Btw. Im using IIS on windows xp pro . and php 5.29-2
thanks so much
Been out in Miami, so I apologize:
The folder permissions have to be set at 755 (chmod)
Thanks for this tutorial. You mention applying this to email, which is exactly what I need to do. I'd like to have form data go into a csv and then have that csv emailed to a recipient. Can someone help? Thanks.
Hi Alpho011. I placed the csv file on the server and created a php file with the recommended codes. However, when I filled out the form and clicked on Submit, the entries were gone but I didn't see the 'Successfully Saved' message, and of course there was no entry into the csv file.
Also when I tested leaving out some fields and clicked on Submit, I did not get the error message in the code. However, I have php 5.11 installed on the computer and all the php forms for another website work well. Do you have any idea what had gone wrong on my side?
Thanks!!
Hi,
Thanks a lot...This one really worked for me:)
thanks so much. It's work (IIS 5.1, php 5.1.1)
How can i redirect to a new page upon successful form submission? thanks!
Brady, do you have any more info on your array idea?
Would the array would with a big array, like 30 items or so?
Sounds like something I would like to do.
Thanks.
Warning: fopen(formTest.csv) [function.fopen]: failed to open stream: Permission denied in /public/html/pdinardo/formtocsv/contactFrm.php on line 215
Any help would be appreciated.
play with php
play with php www.mahaphpcode.com
Hi Johnta1,
Sorry it has been a couple months since I checked this posting. Any size array will work.
Not Run on Browser Server. Proper run on Localhost.
in your smaple code download you have five forms and its very hard to remove them so i can work with it using my bare bones php skills ... help
I am getting an error message and can't seem to fix it, any ideas?
I seem to be getting a similar error to a poster on this thread (payam). I get an error that appears to be a response to the tag. My error reads No file exists at the address “/Users/steve/Desktop/csvCreate/
Sorry, the tag I was referring to didn't show up in my post. I'm referring to the php tag that calls itself "". My error reads No file exists at the address “/Users/steve/Desktop/csvCreate/
when we download the csv file it is in readonly format, how to edit the values without using saveas
Hi, I need someone to build insert this to my website. I can pay with paypal. My email is robertoandrescertain@hotmail.com
Good day - Thank you very much for this. 1 small problem though, I have added a field, credit card number, (also cvv, expiration date, and amount) (using this as a very basic shopping cart) and all the fields work great, except that the last digit of the credit card number is chopped off, and replaced with a 0. I have looked and dug, but unable to find anything that is limiting the numbers to 15 digits. makes no difference in IE, or Firefox. Any suggestions. skyegod@gmail.com
Thanks
Andrew
I need to make a form on a site that asks who a person is and whether they are attending 1 or 2 of multiple events. It looks like this would work great. I'm just wondering if the .csv gets updated by each user that submits the form or if it makes multiple pages.
Thanks,
Jim
@jim10,
It updates the csv!
wow!!! really worked! a million thanks! it's really brilliant.. :)
De nada
if any one need code for php pay $50
Thanks for this great script... I have a question...
My form pass 8 $variables and it writes fine, the first part after writing to the file is the date, that you entered in the form, what I want is to read the file and put it in tables and also have a little search form that the user will enter the date and when submitted, the script look into the file written the find the date entered and show all the complete line where the user submitted before.... can you help find the write direction? hope I make sense... regards
@UTAN
//maybe this
$file = fopen("test.csv", "r") or exit("Unable to open file!");
while(!feof($file)){
if($test == $dateRange){
echo fgets($file). "";
}
}
fclose($file);
Don't know if that will work, but it makes sense for the moment.
Hi,
Its really worked!!!
Thanks
Hi,
It Really Word!
Thanks a ton :)
Hi Alpho011, i have never used PHP before and im confused on what to do after i have put the varibles in to the CSV file?
Can anybody help
Hi,
I copied your code and tried it. When I submit the button the page got refresh but didn't created the csv file. We should manually create the csv file or this code will create the file.
Thanks.
Thank you! I wish I had found this earlier. I created a Certificate Request form for an online class which gets mailed to me. Your form will cut my workload way down and should prevent any errors in transposing.
One question before I get started. I am confused about the session_start section. I have never put anything above a doc type declaration. Is that really where it goes? Thanks again!
I felt problem when I create a doc file. That created of 100% width,but I want the doc of 80% width.
I hope you can help me....
the code given below
$page_content = ''.$gls_cat_name.''.$term_content.'';
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=".$file_name.".doc");
echo ''.''.$ps_title.''.$page_content.'';
just a suggestion but for all you guys who want to avoid errors, how about pluggin in a javascript validation like the JQuery Validation plugin ( http://docs.jquery.com/Plugins/Validation ) or Real Simple Validation (http://www.benjaminkeen.com/software/rsv/) You simple include them in your page and set the value as required and it will do the rest. You don't even have to know Javascript to do it.
Just a thought.
@Trilby:
The session start is needed if your using a session on the page for anything.
It should always go at the top if used.
i m having acturally trying to look at what has been done and whenever i true to view it on IE8 im asked to eiether download the PHP or save it. Is this because you need to have a domain to view thw PHP or is there something else?
Richard
thanks for this info
@Richard: Yes you need a way to host the PHP script.
Hi
Important question
What if someone enters "," comma in comments field, it will shift it to new cell in csv, is'nt that?
So how to avoid that condition?
hello iam ahmad from syria look that code is really useful and iwant try this right now but i thinks its easy to hack yes its
Thanks Alpho, great finding this little nugget of code. Has really helped me with my little Newsletter sign-up feature.
Actually, for some strange the server errors when I submit the form unless I remove the line: if($fp){
With this line removed everything works fine, so I'm still happy :-)
The files don't appear to be hosted anymore - does anyone have a copy please?
Cheeers Darren
Hi, I am new on PHP so i don't know how to use this script in form? Can you please help me that how i can use this script in PHP Format?
Hi,
Can you please post the files. They don't appear when I press the blue link.
Thank You
its not work its aall wasted.
its not work its aall wasted.
im sorry, im a PHP beginner, i found error,
Parse error: syntax error, unexpected $end in C:\xampp\htdocs\sample\sample2.php on line 82
what will i do?
Xten
You are missing a bracket in your php or mine, I am sorry everyone the src files are not not online I took down the hosting looking for a new method.
how about this error?
Access forbidden!
You don't have permission to access the requested object. It is either read-protected or not readable by the server.
If you think this is a server error, please contact the webmaster.
Error 403
localhost
3/9/2011 9:51:31 AM
Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1
So will you be putting up the source files somewhere?
I have looked everywhere and this is exactly what I need.
Thanks
Is creating the CSV file as simple as writing out the list of field names like the example at the top of this page?
Thanks - works a treat...although validation wasn't working straight off the bat. Will have a play!
would love to have a look at the source files. hope you can post them soon.
great work.......i have tried it and it works
But i have a doubt....
In the comments field which is a text area,if two or more lines are typed with the enter key then it comes in the name field.Please specify a step to rectify this.I have a work related to this.
I also would like to get the code, or if someone can tell me how to use what is in this tutorial my php is not great.
Thanks
Im an amatuer and need the script for this but only want name and email
Can you send to me please
redford.michael@gmail.com
Its really gud.
Hi I have followed your excelelnt description and got the form to work and export to a csv file, unfortunately I run into the same problem as a previous poster and if someone puts in a comma or a return, it messes it up in the excel. Also I need a field for other comments so sometimes this can be left blank, so i have left out the checks for empty. I am interetsed in the reponse to put the values in double quotations or the array idea but will need more information as to how to do that, please.
Thanks for the post. Here’s a tool that lets you build your custom web form in minutes – without coding. Just point-and-click
dear sir,
I have just modified ur code... everything seems fine till i give submit
after that nothing comes where will the .csv file be saved
could u pls help me on that
this is not working
last line error its coming
how to cleared its

![Microsoft Office Excel 2007 [Old Version]](http://ecx.images-amazon.com/images/I/41d55075txL._SL75_.jpg)

Lgali 3 years ago
thanks for this info