Flat log file

Renegade's picture

He has: 3,022 posts

Joined: Oct 2002

I'm currently wanting to learn about flat file databases so decided to make a flat file log.

I have the following code:

<?php
  $file
= \"log.txt\";
 
$filetr = fopen($file, \"r+\");
 
$log_string = array(
    gethostbyname(
$_SERVER['HTTP_HOST']),
    date(\"F j Y\"),
    date(\"g:i A\"),
   
$_SERVER['HTTP_REFERER'],
   
$_SERVER['PHP_SELF'],
   
$_SERVER['HTTP_USER_AGENT']
  );
 
$data = implode(\"~\", $log_string);
  fwrite(
$filetr, $data);
 
$filetr = fclose($filetr);
?>

I would like it to write to the beginning of the file pushing the next one down, however, it just overwrites.

Some help please?

Renegade's picture

He has: 3,022 posts

Joined: Oct 2002

I figured it out now, heres the code that I used:

<?php
  $file
= \"log.txt\";
 
$filetr = fopen($file, \"r+\");
 
$data_old = fread($filetr, filesize($file));
 
$filetr = fclose($filetr);
 
$filetr = fopen($file, \"w+\");
 
$log_string = array(
    gethostbyname(
$_SERVER['HTTP_HOST']),
    date(\"F j Y\"),
    date(\"g:i:s A\"),
   
$_SERVER['HTTP_REFERER'],
   
$_SERVER['PHP_SELF'],
   
$_SERVER['HTTP_USER_AGENT']
  );
 
$data_new = implode(\"~\", $log_string);
 
$data = $data_new . \"\n\" . $data_old;
  fwrite(
$filetr, $data);
 
$filetr = fclose($filetr);
?>

Laughing out loud

Renegade's picture

He has: 3,022 posts

Joined: Oct 2002

I'm using

<?php
gethostbyname
($_SERVER['HTTP_HOST'])
?>

to get an IP but I realised that I was getting the IP of my host, how do I get the IP of the viewer of my site?

Abhishek Reddy's picture

He has: 3,348 posts

Joined: Jul 2001

http://www.php.net/manual/en/reserved.variables.php#reserved.variables.server

Quote: 'REMOTE_ADDR'
The IP address from which the user is viewing the current page.

'REMOTE_HOST'
The Host name from which the user is viewing the current page. The reverse dns lookup is based off the REMOTE_ADDR of the user.

Note: Your web server must be configured to create this variable. For example in Apache you'll need HostnameLookups On inside httpd.conf for it to exist. See also gethostbyaddr().

Renegade's picture

He has: 3,022 posts

Joined: Oct 2002

Thanks.

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.