How to write user input into text file using php

02nd, January 2018 By

To write text file using php with the data entered by user you need to follow these steps:

Step 1:

Create a form through which user will enter the data that will be written to the file

<form method="post">Data1 <input type="text" name="data1" />

 Data2<input type="text" name="data2" />
<input type="submit" value="submit" /></form>

This form will look like this:

 

Form data

Step 2:

You will get data in $_POST to write it to text file first you have to open file in write mode after that you can write particular data into it make sure to close the file using fclose function .


<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $_POST['data1'] . 'mydata:' . $_POST['data2'];
$stringData .= "\n";
fwrite($fh, $stringData);
fclose($fh);

?>

Here you can see testFile.txt is opened by fopen function for writing data and after that the data received in post is written to the text file .the file will look like this:

File Written

Here you can see data in file with mydata: to separate the different inputs .

Leave a Reply

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