Save data from a form to txt by using fwrite

Lets say you have a newsletter subscription form on your web site. But you just want to collect e-mails of people and write them down in a file. In order to do this, we need to read the input tag’s value added by the user and use php function fwrite to add them.

Here is the code for the form we gonna use:

<form action="" method="post">
	<input type="text" name="email" value="Your e-mail" />
	<input type="submit" value="Submit" />
</form>

The user will be on the same page, after clicking Submit, because we haven’t written anything in action=””. If you want you can create function that echo a message like “Thanks for subscribing!”

The name=”email” will be used in our php to get the input value. First we need to create a variable for our txt file and open it with the proper rights:

	$myFile = "mail.txt";
	$fileHandling = fopen($myFile, 'a+') or die("the file cannot be open");

fopen is a built-in function as well as fclose and fwrite. In order to use fwrite, we will have to use also fopen and fclose. First we have to open the file, than write to it and in the end – close it. All those 3 functions require that you specify the file and then the rights to edit it. We use the variable $myFile, for the file we have, and rights a+. A full list of all possible modes to open and edit files can be found on W3Schools. a+ means that we can write to the file and preserve the previous content. If you use w or w+ each new record in the file will overwrite the previous one, and we don’t want that. The last part of this php code is for error handling (…or die(“the file cannot be open”);)

Next it’s time to write in our file:

	$email = $_POST['email'] . ", ";
	fwrite($fileHandling, $email);

We are using post as method in our form, that’s why we will do the same in the php, too. Post is better than get in this case, because we don’t wont the e-mail to be displayed in the url. There is a comma added in the end of the email variable to differentiate where an email ends. On the second line we pass the variable for file handling (where we open the txt file) and the variable for e-mail.

The last line of our code is for closing the file:

fclose($fileHandling);

DOWNLOAD CODE

A step further you can do is, validate the input data in the form, to make sure it’s an email.

Php fwrite from tizag

Php fwrite function – w3schools

Fwrite function – about.com

Fwrite function – the php manual

1 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *