0

I will like to save the output of the following form action in a textfile like this:

var1
var2
var3

Example form action:

<form action="myform.php" method="post">

<input type="hidden" name="var1" value="var1">
<input type="hidden" name="var2" value="var2">
<input type="hidden" name="var3" value="var3">

<input type="submit" name="formSubmit" value="Submit">
</form>

Example myform.php

<?php

  $fs = fopen("mydata.txt","w");
  fwrite($fs,$_POST['var1']);
  fwrite($fs, "\n");
  fwrite($fs,$_POST['var2']);
  fwrite($fs, "\n");
  fwrite($fs,$_POST['var3']);
  fwrite($fs, "\n");
  fclose($fs);


?>

However, the output is:

var1var2var3

What could i do to fix it?

Ting Ping
  • 1,145
  • 7
  • 18
  • 34

3 Answers3

2

If you are using windows you will not see those variables in new lines. This is because Windows uses \r\n as line terminator.

var1\nvar2\nvar3\n in windows will render as

var1var2var3

But in Linux or Unix (\n line terminating) it will render as

var1
var2
var3

So you have to use \r\n instead of \n like this

fwrite($fs, "\r\n");

This will render the values in new line on any operating system.

Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
0

Do you want to do it for debugging purpose or for actual storage in your application? Either way if it is not supposed to be read by users directly as a text file you can save your POST array using var_export function.

<?php
file_put_contents("C:/debug.txt", var_export($_POST, true));
?>

When you use var_export, what you get in file is a valid PHP code, so if you want later on you can use it as an array and get your data back in application.

deej
  • 2,536
  • 4
  • 29
  • 51
0

A predefined constant PHP_EOL is available in PHP4 since PHP 4.3.10 and in PHP5 since PHP 5.0.2.

It will add correct end of line for any operating system.

fwrite($fs, PHP_EOL);

Use this if you are developing your project in one operating system and deploy it in a server that is running a different operating system.