How to append string to text file using PHP

Last updated on March 18th, 2022 at 07:59 am

Click to rate this tutorial!
[Total: 2 Average: 3]

In this tutorial we are going to see steps on appending string to a text file or any file and then view that file live line by line.

For the purpose of showing the details I am going to have a simple HTML form that accepts the string to be added to the file. Create a file named append.php and add the code below

<form action="<?php $PHP_SELF?>" method="post">
<input value="" type="text" name="addition"/><br/>
<input type="submit"/>
</form>

Just focus on that input field with name “addition” that is the value we are going to read in PHP.

Now for processing the form data and add that to string to a file we are going to add the below php code to the same append.php file

<?php
if($_POST['addition'])
{
       $fn = "myfile.txt";
       $d=date("Y-m-d h:i:sa");
        $file = fopen($fn, "a+");
        fwrite($file, $_POST['addition']."_".$d."_"."\n");
}
fclose($file);
?>

 In the code above we are

  • First check whether it is a post request then proceed with processing data
  • Defining a file named myfile.txt
  • some random variable I am using date as an example
  • Opening the file for appending data fopen($fn, “a+”)
  • Writing the data from post request using fwrite and also add the variable along with the data

So the entire file (append.php) will look like this

<form action="<?php $PHP_SELF?>" method="post">
<input value="" type="text" name="addition"/><br/>
<input type="submit"/>
<?php
if($_POST['addition'])
{
       $fn = "myfile.txt";
       $d=date("Y-m-d h:i:sa");
        $file = fopen($fn, "a+");
        fwrite($file, $_POST['addition']."_".$d."_"."\n");
}
fclose($file);
?>

How to view the file line by line (Bonus)

For viewing the file just use the below foreach statement and add it just before the fclose statement and within the POST if block.

<?php
if($_POST['addition'])
{
       $fn = "myfile.txt";
       $d=date("Y-m-d h:i:sa");
        $file = fopen($fn, "a+");
        fwrite($file, $_POST['addition']."_".$d."_"."\n");
echo "Reading The File";
foreach(file($fn) as $line) {
        echo $line."<br>";
}
}
fclose($file);
?>

Demo

Click to rate this tutorial!
[Total: 2 Average: 3]

One reply on “How to append string to text file using PHP”

Leave a Reply

Your email address will not be published.