0

I'm trying to save 3 variables to a csv file. I get the variables data then I'm creating an array containing them. I can open the file and write it. I would like to store the following data on every page load: - referer - user agent - date

My problem is that on every page load it rewrites the file instead of just inster the new data.

Any idea? Every comment is appreciated.

<?php

session_start();

if ( !isset( $_SESSION["origURL"] ) )
$_SESSION["origURL"] = @$_SERVER["HTTP_REFERER"];

$referer = @$_SERVER['HTTP_REFERER'];
$userAgent = @$_SERVER['HTTP_USER_AGENT'];
$date = date('Y-m-d H:i:s');

$visitorData = array("referer", "userAgent", "date");
$result = compact($visitorData);
print_r($result);

$fp = fopen('file.csv', 'w');

foreach ($result as $fields) {
    fputcsv($fp, $result, $delimiter = ',', $enclosure = '"');
}

fclose($fp);
exit();

?>

1
  • append mode use - $fp = fopen('file.csv', 'a'); Commented Jul 3, 2016 at 11:54

1 Answer 1

1

As @splah58 says, you must open your file in append mode to add data, like this :

if( !isset( $_SESSION["origURL"] ))
  $_SESSION["origURL"] = @$_SERVER["HTTP_REFERER"];

$referer = @$_SERVER['HTTP_REFERER'];
$userAgent = @$_SERVER['HTTP_USER_AGENT'];
$date = date('Y-m-d H:i:s');

$visitorData = array("referer", "userAgent", "date");
$result = compact($visitorData);
print_r($result);

$fp = fopen('file.csv', 'a'); // 'a' means 'append' instead of 'w' for 'writing' which always delete the file's content

foreach ($result as $fields) {
  fputcsv($fp, $result, $delimiter = ',', $enclosure = '"');
}

fclose($fp);
exit();
Sign up to request clarification or add additional context in comments.

7 Comments

You are right! Thank you! I experienced one more weird behavior. Do you have any idea why does it log 3 times a row in one session?
That's because the PHP page is loaded 3 times in one session :)
I mean one page load = 3 lines of data.
$result may contains 3 content
When I print it I get this: Array ( [referer] => localhost:8088/php-log/ref.html [userAgent] => Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36 [date] => 2016-07-03 18:39:51 )
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.