rainerbrunotte
rainerbrunotte

Reputation: 907

JQuery & AJAX call to append to custom TXT log file

I am trying to append date to a custom log file to track clicks on a specific link, however everything in the TXT file gets overwritten:

$('#cal').click(function() {
$.ajax
    ({ 
        url: 'caltrack.php',
        data: {caltrack: 'true'},
        type: 'post',
        success: function()
        {
          console.log('success');  
        }
    });
});

PHP:

<?php
error_reporting(E_ALL);
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
$date = date('Y-m-d h:i:s a', time());
$data = $date.' - '.$ip.'';
$f = fopen('caltrack.txt', 'w+');
fwrite($f, $data);
fclose($f);
?>

How can I append a new row of text everytime?

Upvotes: 2

Views: 786

Answers (2)

Tayyab
Tayyab

Reputation: 1217

Change your php code to the following:

<?php
    error_reporting(E_ALL);
    $ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
    $date = date('Y-m-d h:i:s a', time());
    $data = $date.' - '.$ip.'';
    $f = fopen('caltrack.txt', 'a');
    fwrite($f, $data);
    fclose($f);
?>

So what were you doing wrong? Actually you were opening a file in w+ mode that open a file for read/write and erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file. Thus everything getting overwritten. Here if you open file in a or a+ mode then you can append your data to your file.

Further details about php files can be found here.

Upvotes: 1

Julien Lachal
Julien Lachal

Reputation: 1141

Don't open your file with w+ because it will truncate the whole file, but rather with mode a as in "append".

See fopen

Upvotes: 2

Related Questions