Hmm...I haven't had much luck using a combination of functions to get this working like file() etc. so I instead of boring you with unsuccessful code, I was wondering if anyone had thoughts on this?

NEED
Have a file I append IP's of visitors to a site. I want to keep X number of the LAST lines in that file ie: the last X number of vistors' IPs.

IDEA
Open the file.
Grab X number of the last lines.
Save file with these X number of last lines.

I bet there's an elegant, tight way of doing this..but how?

Thanks, :)
Kev

Please bore us with unsuccesfull code, so we can make it succesfull. That is the entire point of this forum.

We are glad to help people with their own code, but we don't like writing code for people that don't show effort or order us to make the code.

~G

commented: Nicely put :) +19

Hi Graphix,

Many thanks for the reply. Ok...boring code coming..at least the latest one. My preference is to grab the last X lines in the file but as you know, this wasn't working out. So I thought I'd try it from the angle of grabbing the first X lines instead and if that worked, try to prepend the insertion of the new content instead of the current append.

Anyhow..here goes: (IPs.html - the file being manipulated)

$fileASarray=file('IPs.html');
$keeplines=array_slice($fileASarray,30);
$newfile=implode("\r\n",$keeplines);
$fp=fopen('IPs.html','w+');
fwrite($fp,$newfile);
fclose($fp);

Please note:

  • \r\n - developing on a Windows 7 localhost using WAMP
  • I tried this on a file with >30 lines to be sure (then later with a smaller $keeplines to be doubly sure). Ideally I wanted this to not fuss if the file was smaller than the line count but I was just wanting to get this 1st step right first before adding that in.

Cheers!

The code is a bit more complex, you first need to read, then divide it, then get the last X amount of lines, and then write the result into the file:

<?php
// Reading file content

$file = "IPs.html";
$fh = fopen($file,"r");
$content = fread($fh,filesize($file));
fclose($fh);

// Splitting the content of the file into an array, divided by a \n

echo "The content of the file, split by a \n, as an array:<br /><br />";

$linesArray = split("\n",$content);

print_r($linesArray);

$linesAmount = count($linesArray);

// Making a new array:

$keepLinesAmount = 5; // The amount of lines that need to be kept (from the bottom)
$startLine = $linesAmount - 5;
echo "<br /><br />StartLine:".$startLine;

$i = 0;
for (; $startLine < $linesAmount; $startLine++) {
$keptLinesArray[$i] = $linesArray[$startLine];
$i++;
}

echo "<br /><br />The last ".$keepLinesAmount." of the linesArray:<br /><br />";

print_r($keptLinesArray);

// Making the new content

$new_content = "";
for ($d = 0; $d < $keepLinesAmount; $d++) {
if (($d + 1) == $keepLinesAmount) { // If the end of the array has been reached
$new_content .= $keptLinesArray[$d];
} else {
$new_content .= $keptLinesArray[$d]."\n";
}
}

// Writing the new content to the file

$fh = fopen($file,"w+");
fwrite($fh, $new_content);
fclose($fh);
?>

~G

Hi Graphix!

Thanks for thoughts in the code, much appreciated. I tried the code out..I did change

<?php
echo "The content of the file, split by a \n, as an array:<br /><br />";
$linesArray = split("\n",$content);

~G

To

echo '<br />The content of the file, split by a \\r\\n, as an array:<br /><br />'; 
$linesArray = split("\r\n",$content);

so it would display nicely and work on WAMP Windows 7.

Unfortunately it didn't work..I just keep getting an ever growing IP list. There is the error too on the page:
StartLine:-4
Notice: Undefined offset: -4 in C:\wamp\www\IP related\testip.php on line 55

Notice: Undefined offset: -3 in C:\wamp\www\IP related\testip.php on line 55

Notice: Undefined offset: -2 in C:\wamp\wwwIP related\testip.php on line 55

Notice: Undefined offset: -1 in C:\wamp\www\IP related\testip.php on line 55


In case it makes a difference, here's the code preceeding your's that picks up the IP and appends it:

//Grab the IP of the visitor
function get_ip_list() { 
$tmp = array(); 
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && strpos($_SERVER['HTTP_X_FORWARDED_FOR'],',')) { 
$tmp += explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']); 
} elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { 
$tmp[] = $_SERVER['HTTP_X_FORWARDED_FOR']; 
} 
$tmp[] = $_SERVER['REMOTE_ADDR']; 
return $tmp; 
} 
$iptmp = get_ip_list(); 
$ip = implode(",",$iptmp);                                                                                                                
echo '<a href=' . 'http://ip-whois-lookup.com/lookup.php?ip=' . $ip . '>' . $ip . '</a>';

//Append to IPs.html the date/time & IP vistor info
$logfile= 'IPs.html';
$logdetails=  date("j-M-Y, g:i a") . ' from ' . '<a href=' . 'http://ip-whois-lookup.com/lookup.php?ip=' . $ip . '>' . $ip . '</a>'; 
$fp = fopen($logfile, "a");  
fwrite($fp, $logdetails); 
fwrite($fp, "<br />"); 
fclose($fp);

Looking forward to the insights

The error you discribed means that the contents of the file were not succefully splitten into an array. $linesAmount counts the array and returns that. If the array amount is lower as 5, than the code doesn't work, because you can't get a negative amount as startLine.

Assuming your file consists out of more than 5 lines, you should adjust the split() so that it correctly splits the array (meaning you need to use the correct delimiter).

Print the arrays and the variables so that you know when it goes wrong.

It would be of great help to post a small part of your text file, so I can test my code out myself. Make sure that you change the IP's to XX.XX.XXX.XXX for privacy reasons.

~G

!!!!
DUH to me. :icon_rolleyes:

Thanks for your persistence Graphix...the problem here is that the log file was simply appending the new IPs onto the end of the line ie: one long line.
Your interpretation of the error code got me looking at the contents of the log as opposed to how it rendered in the browser (which was of course multi-lined).

So..slapping a \n on the end of the lines put out by fwrite did the trick. Cheers!
I just have to go off and put in some logic to stop the code from freakin' out when there are less than the $keepLinesAmount number of lines...hopefully I can figure that out myself.

Cheers! Thanks for your help! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.