0

I have a PHP script that records visitor data into a csv file.
I would like the visitor data to append new information to the second line of the csv file.
Right now, new data appends to the very bottom of the files, and the list becomes very long.

$cvsData = $ip  . "," . $host . "," . $os  . ","  . $currentDate . "," . $TIME ."\n";

$fp = fopen("C:\\WWW\\LOG\\LOG.CSV","a");

fwrite($fp,$cvsData); // Write information to the file
fclose($fp); // Close the file
Burhan Ali
  • 2,258
  • 1
  • 28
  • 38
man0man
  • 37
  • 6
  • You will need to read the file into an array, alter the array with your new vales, and then save it again. – John Conde Apr 18 '14 at 20:18
  • Because the only solution may require you to load a very large file into memory, you should consider if it's worth the trade off. The list will keep growing no matter where you put the new line. – jackfrankland Apr 18 '14 at 20:29

2 Answers2

0

This is possible, but more complex than simply appending to a file:

You have to implement a short routine for this:

  • open the file for reading, read the content into a buffer and close the file
  • separate first (header) line and the rest of the file
  • open a new, temporary file for writing
  • write the header line, then the new line, then the rest of the buffer
  • close the temporary file
  • last move the temporary file to the final name and location, thus overwriting the old file

A variant might be to move the old file aside as a backup copy and move the new, temporary file in its place.

arkascha
  • 41,620
  • 7
  • 58
  • 90
0

I assume that 'write to the second line' means the same as 'keep the first line and remove everything else' and not 'remove the header from first line, insert the new data as the first line and write the header as the first line again'

// get the first line
// http://stackoverflow.com/questions/4521936/quickest-way-to-read-first-line-from-file
$f = fopen($file, 'r');
$csvHead = fgets($f);
fclose($f);

// your data
$csvData = $ip  . "," . $host . "," . $os  . ","  . $currentDate . "," . $TIME ."\n";

// add your code to the end..

$f = fopen($file,"w");
fwrite($f,$csvHead); // Write information to the file
fwrite($f,$csvData); // Write information to the file
fclose($f); // Close the file

not the nicest of code, but should work, but you only have the latest visitors details.

there are many other, better, solutions for tracking visitors to websites (google analytics?), but you could keep your current script unmodified and check out 'tail for win32' - it lets you monitor files from additions to the bottom http://tailforwin32.sourceforge.net

Jonathan
  • 1,542
  • 3
  • 16
  • 24