Save Data To Text File Using PHP

This tutorial will teach you on how to save data on text file using php. The feature of this tutorial is it will allow you to save information without using any database. It also provide a confirmation message that you have successfully save the data in the text file. To understand more this tutorial follow the steps bellow.

Creating Our Form

The code bellow will display the form and the confirmation message generate by our php server. Copy the code bellow and save it as "index.php".
  1. <?php
  2. if( isset($_SESSION['ERRMSG_ARR']) && is_array($_SESSION['ERRMSG_ARR']) && count($_SESSION['ERRMSG_ARR']) >0 ) {
  3.         foreach($_SESSION['ERRMSG_ARR'] as $msg) {
  4.                 echo '<span style="color:red;">',$msg,'</span>';
  5.         }
  6.         unset($_SESSION['ERRMSG_ARR']);
  7. }
  8. ?>
  9. <form action="save.php" method="POST">
  10. <span style="display: inline-block; width: 150px;">Name</span><input type="text" name="name" required="required" /><br>
  11. <span style="display: inline-block; width: 150px;">Age</span><input type="text" name="age" required="required" /><br>
  12. <span style="display: inline-block; width: 150px;">Gender</span><select name="gender"><option>male</option><option>female</option></select><br>
  13. <span style="display: inline-block; width: 150px;">&nbsp;</span><input type="submit" value="Save" />
  14. </form>

Creating Our Save Scripts

the code bellow will allows us to save data into the text file using the "fwrite" function in php. Copy the code bellow and save it as "save.php".
  1. <?php
  2. $errmsg_arr = array();
  3. $errflag = false;
  4. $name   = trim($_REQUEST["name"]);
  5. $age    = trim($_REQUEST["age"]);
  6. $gender         = trim($_REQUEST["gender"]);
  7. $filename       = "informationlist.txt";
  8. $MyFile         = fopen($filename, "a");
  9. $newline=$name.','.$age.','.$gender."\r\n";            
  10. fwrite($MyFile, $newline);
  11. fclose($MyFile);
  12. $errmsg_arr[] = $name.' data has been save to '.$filename.' file';
  13. $errflag = true;
  14. if($errflag) {
  15.         $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
  16.         session_write_close();
  17.         header("location: index.php");
  18.         exit();
  19. }
  20. ?>
That's it you've been successfully a system that save data to text file.

Comments

Thank You Very Much for this code .

Add new comment