Dynamically Create Text File Using PHP

Here we will show how you can create a Dynamically Text File using PHP. In this code can create a text file with content dynamically when user submit the form inputs. The code use PHP POST method that create a text using PHP functions fopen() to open an existing file and if not exist it will create a new file, fwrite() insert content in the text file, and fclose() safely close the connection between the opened file.

First we will create a form take input from user. So create index.php file

				
					<!DOCTYPE html>
<html>
  <head>
    <title>Inflay.com | Dynamically Create Text File Using PHP</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  </head>
  <body>
      <h3>Dynamically Create Text File Using PHP</h3>
      <br />
      <form action="" method="post">
            <label for="country">File Name</label>
              <input type = "text" id="file_name" name="file_name" value = "">
            <label for="country">Content</label>
              <textarea id="content" name="content"></textarea>
            <br/>
            <button name="send" id = "send">Create</button>
      </form>
  </body>
</html>
				
			

Below is code for create file after the click create button. Put below code in index.php file.

				
					<?php
  if(isset($_POST['send'])){
    $content = $_POST['content'];
    $file_name = $_POST['file_name'];
    $path = "store"; 
    $file = fopen($path."/".$file_name.".txt", 'w'); 
    fwrite($file, $content);
    fclose($file);
    header("location:index.php");
  }
?>
				
			

I hope this article helps you.
Thanks for visiting Inflay.com .