1

I have a simple hit counter where I save the IP and country of visitors, but after some hits the file where I write the visits fills with empty lines

This is the result:

<myip>|GR







<myip>|GR



<myip>|GR

<myip>|GR
<myip>|GR

This is the code:

<?php
    $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    $location = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));

    $entries = file("hitcounter.txt");
    array_push($entries,$ip."|".$location->country);

    $newEntries=implode($entries,"\n");

    $fp = fopen("hitcounter.txt" ,"w");
    fputs($fp , $newEntries);
    fclose($fp);

    function echoVisits(){
        $entries = file("hitcounter.txt");
        echo count($entries);
    }
?>

So why do I end up with a file with empty lines?

3
  • 1
    And your question is? Commented Apr 8, 2015 at 9:49
  • I think he wants to omit extra lines from code. @Rizier123 Commented Apr 8, 2015 at 9:51
  • @Rizier123 ,I though it was obvious... as Testing said I don't want the empty lines... Commented Apr 8, 2015 at 9:52

1 Answer 1

3

You just have to change this:

$newEntries=implode($entries,"\n");

$fp = fopen("hitcounter.txt" ,"w");
fputs($fp , $newEntries);
fclose($fp);

to this:

file_put_contents("hitcounter.txt", $entries);

Because if you read the file into the array with file() you already have the new line characters at the end of each element, so if you implode it you going to add a new line character to each element.

That you have the new line character also in your new entire you just have to append it in your array_push like this:

array_push($entries, $ip."|". "GR" . PHP_EOL);
                                   //^^^^^^^

Also if you don't use the data from the file anywhere else in your code you could also just append the new entry, so your could could look something like this:

$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
$location = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));

file_put_contents("hitcounter.txt", $ip."|". $location->country . PHP_EOL, FILE_APPEND);

function echoVisits($file){
    return count(file($file));
}
Sign up to request clarification or add additional context in comments.

Comments

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.