Search code examples
phpformatnewlinewhitespace

How to make spaces come in file


I am trying to make a page which logs text with the time to a file.

index.html:

<html>

<form action="process.php" method="POST">
<input name="field1" type="text" />
<!-- <input name="field2" type="text" /> -->
<input type="submit" name="submit" value="Save">
</form>

</html>

process.php:

<?php
if(isset($_POST['field1'])) {
    $date = date('Y-m-d His');
    $data = "\n" + "<pre>$date</pre>" + $_POST['field1'];
# if(isset($_POST['field1']) && isset($_POST['field2'])) {
#    $data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
#    $filename = date('YmdHis').".txt";
    $filename = "log.txt";
    if (!file_exists($filename)) {
        $fh = fopen($filename, 'w') or die("Cannot create file");
    }
    $ret = file_put_contents($filename, nl2br($data), FILE_APPEND | LOCK_EX);
    if($ret === false) {
        die('There was an error writing this file');
    }
    else {
        echo "$ret bytes written to $filename";
    }
}
else {
   die('No post data to process');
}
?>

log.txt:

0

When I input "test" log.txt shows "0".

How do I make it output the time and the text on a new line each time there is input.


Solution

  • I fixed it.

    I removed + and replaced it with periods, I removed:

     if (!file_exists($filename)) {
           $fh = fopen($filename, 'w') or die("Cannot create file");
       }
    

    because it was not needed, I removed pre tags because they were not needed.

    process.php:

    <?php
    if(isset($_POST['field1'])) {
        $date = date('Y-m-d ');
        $data =  "\n" . "$date" . $_POST['field1'];
        $filename = "log.txt";
        $ret = file_put_contents($filename, $data, FILE_APPEND | LOCK_EX);
        if($ret === false) {
            die('There was an error writing this file');
        }
        else {
            echo "$ret bytes written to $filename";
        }
    }
    else {
       die('No post data to process');
    }
    ?>
    

    Now it outputs the data properly.

    log.txt:

    2021-06-22 test