-2

I have a series of variables in my PHP script that are defined via POST.

For example:

$From = "";
if( isset($_POST['From']) )
{
    $From = $_POST['From'];
}

How can I create a log file (not a database, just basic txt) to capture the POST values? This is part of a conferencing web app, so there is no way to display the content "on screen". I need to dump it to a file on the server.

alias51
  • 8,178
  • 22
  • 94
  • 166
  • http://uk3.php.net/fwrite – putvande Feb 01 '14 at 13:34
  • There is also `error_log("From ".$from)` – meda Feb 01 '14 at 13:36
  • http://stackoverflow.com/questions/6947358/how-to-include-get-post-data-in-php-error-log – Shahrokhian Feb 01 '14 at 13:39
  • Are you sure you want to write it to a file? An interactive debugger (like for instance an `xdebug` & netbeans or phpstorm combo) will enable you to set breakpoints, inspect variables, and more, without littering your code with all kind of debug writes. If you really just want to log posts, configuring apache to log the entire request bodies of all requests is also easier then doing it in PHP (but with a little less output format control). – Wrikken Feb 01 '14 at 13:40

4 Answers4

1

Try something like this

    $post_dump = print_r($_POST, TRUE);
    $log = fopen('log.txt', 'a');
    fwrite($log, $post_dump);
    fclose($log);
Subodh Ghulaxe
  • 18,333
  • 14
  • 83
  • 102
1

JSON-encode your array using json_encode() and store it to a file:

$data = json_encode($_POST);
file_put_contents('file.txt', $data);

When you want to retrieve the contents, you can use file_get_contents() or similar and then use json_decode() to decode the JSON-string back into an array / object.

Using JSON makes the interchanging of data easier, and you don't need to parse the text file to retrieve information out of it. Just use json_decode() and be done with it. However, I suggest you use a database instead of a plain text file to store this information, as it gives you more control.

As @Wrikken noted in the comments below, you could use the FILE_APPEND flag - it allows you to append the data to the file instead of overwriting it.

file_put_contents('file.txt', $data, FILE_APPEND);
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
0

try this...

<?php
  $From = "";
  if( isset($_POST['From']) ){
      $file = fopen("test.txt","w");
      fwrite($file,$From);
      fclose($file);
   }
?>
meda
  • 45,103
  • 14
  • 92
  • 122
user1844933
  • 3,296
  • 2
  • 25
  • 42
0

Something like this

$arr = array();
foreach($_POST as $key=>$value);
{
    $arr[] = $key.'='.$value;
}
file_put_contents('log.txt', implode(',', $arr), FILE_APPEND);
Joris Ros
  • 389
  • 2
  • 6