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">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  </head>
  <body>
    <div class="container">
      <h3>Dynamically Create Text File Using PHP</h3>
      <br />
      <form action="" method="post">
        <div class = "row">  
          <div class="col-md-3">
            <label for="country">File Name</label>
              <input type = "text" class="form-control" id="file_name" name="file_name" value = "">
          </div>
        </div>
        <div class = "row">  
          <div class="col-md-3">
            <label for="country">Content</label>
              <textarea class="form-control" id="content" name="content"></textarea>
          </div>
        </div>
        <div class = "row">
          <div class = "col-md-3">
            <br/>
            <button class="btn btn-primary" name="send" id = "send">Create</button>
          </div>  
        </div>  
      </form>
    </div>
  </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 .