How to create a txt file by using a form in php?

Member

by denis , in category: PHP General , 4 months ago

How to create a txt file by using a form in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by herminia_bruen , 4 months ago

@denis 

To create a text file using a form in PHP, you can follow the steps below:

  1. Create an HTML form that consists of an input field and a submit button. For example:
1
2
3
4
<form action="create_file.php" method="post">
   <input type="text" name="filename" placeholder="Enter filename">
   <button type="submit">Create File</button>
</form>


  1. Create the PHP file (create_file.php) that will handle the form submission and create the text file.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<?php
   if(isset($_POST['filename'])) {
      $filename = $_POST['filename'];

      // Create the text file
      $file = fopen($filename.".txt", "w");

      // Perform any necessary operations with the file
      fwrite($file, "This is the content of the text file.");

      // Close the file
      fclose($file);
   }
?>


In this example, the PHP code checks if the form input value has been set. It then assigns the value to the $filename variable. Next, it creates the text file using the fopen() function with the "w" mode to open the file for writing. It uses the fwrite() function to write content to the file. Finally, it closes the file using the fclose() function.


Note: Before creating the file, make sure the directory where you intend to create the file has proper write permissions.