Saving Form Field Data To Text and/or Excel Files With PHP



Take Any Contact Form Field and Store the Information to Text File or Excel Database

If you have been following along, by now you have a basic form that sends a visitors email address to you via email, and a conformation message to your visitor with a thank you message.  Now lets say you wanted to store that email address into a text file on the server for use with another application, or backup.

The way this is done is by first creating a blank .txt file and uploading it to your server.  Then you will need to give it permissions of 777 so the script can open and write to the file.

For your php script to open the text file you will need to place this into your code.  In this example we assume you named your text file "email".

$fh = fopen("email.txt", "a");

The "a" you see is how the data will be entered into the file.  In this example we are placing the new email address below the rest of them.

r = Opens the file for reading only and places the file pointer at the beginning of the file.

r+ = Opens the file for reading and writing and places the file pointer at the beginning of the file.

w = Opens the file for writing only and places the file pointer at the beginning of the file. If the file does not exist, it attempts to create it.

w+ = Opens the file for reading and writing and places the file pointer at the beginning of the file. If the file does not exist, it attempts to create it.

a = Opens the file for writing only and places the file pointer at the end of the file. If the file does not exist, it will try to create it (What we will use).

a+ = Opens the file for reading and writing and places the file pointer at the end of the file. If the file does not exist, it will attempt to create it.

Then the next step is to tell it what to write to the file.  Note again the use of the "$email" to place the form data into the text file.

fwrite($fh, $email);

Then we need to close the file.

fclose($fh);

So your complete code looks like this.

<?PHP
$email = $_POST["emailaddress"];

$to = "you@youremail.com";
$subject = "New Email Address for Mailing List";
$headers = "From: $email\n";

$message = "A visitor to your site has sent the following email address to be added to your mailing list.\n

Email Address: $email";

$user = "$email";
$usersubject = "Thank You";
$userheaders = "From: you@youremailaddress.com\n";

$usermessage = "Thank you for subscribing to our mailing list.";

mail($to,$subject,$message,$headers);

mail($user,$usersubject,$usermessage,$userheaders);

$fh = fopen("email.txt", "a");
fwrite($fh, $email);
fclose($fh);

?>

<html>
<body>
<table width="400" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
<div align="center">Thank You, Your Information Has Been Submitted</div>
</td>
</tr>
</table>
</body>
</html>

 

Previous   |  Next

Special Package Offer

    Discounted deal on all of our php contact form scripts as a bundle package