PHP program to create a .txt file and write some content in it.

Write a PHP program Create a .txt file & write content in it


In this tutorial, you will learn how to Create a .txt file & write content in it in php, so basically it means we are creating a file by coding it named as newfile.txt and we are storing or writing data in that created file.

Below is the php script to Create a .txt file & write content in it in php.

<html>
<head>
    <title>PHP Script Create a .txt file & write content in it in PHP</title>
</head>
<body>

    <h2>Write a PHP program Create a .txt file & write content in it</h2>

    <form action="" method="POST">
        <textarea name="text" rows="5" cols="40"></textarea><br>
        <input type="submit" name="ok"/>
    </form>

    <?php
        if($_POST)
        {
            $txt = $_POST['text'];

            $myfile = fopen("newfile.txt","w");//create a file

            if(fwrite($myfile,$txt) === false) //write a file
            {
                echo "Error in writing!!!";
            }
            else
            {
                echo "File Created & Updated Successfully";
            }

            fclose($myfile);
        }
    ?>

</body>
</html>


Thanks for reading.