Search code examples
phpcsvfputcsv

PHP array to csv - Always rewrites the file


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();

?>


Solution

  • 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();