Skip to content
Advertisement

Trying to write variable to text file but it shows no errors but doesn’t work

I am trying to make a bit of code so when someone visits my website it logs their public ip onto my server for access for something else. I have this code below

<?php
    //gets the users public ip
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];
    if(filter_var($client, FILTER_VALIDATE_IP))
    {
        $ip = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
    {
        $ip = $forward;
    }
    else
    {
        $ip = $remote;
    }
    //access the file on server
    $file = fopen("../../UserData/AccountDetails.txt", "a");
    $found = false;
    if ($file) {
        while(!feof($file) or $found) {//if it isnt the end of the file or found is found is false loop again
            $line = fgets($file);
            if ($line != $ip) {
                $found = false;
            } elseif ($line == $ip) {
                $found = true;
            }
        }
        if (!$found) {
            fwrite($file, $ip);
        }
        fclose($file);
    } else {
        echo "<script>alert('error somewhere');</script>";
    }
?>

This gets the users public ip, however when it checks the txt file is it already exists and if it doesnt to write the ip onto it, it just doesnt work but no errors arise. Im not sure on what ive done wrong or right.

Advertisement

Answer

You are opening the file in append mode a, this means that you are at EOF already and can’t seek back. You should open it in read/write mode like r+, remember also to add a newline character when you fwrite the new IP address. Another bug is that if you find the IP and it’s not the last, at the next iteration found will be false again, change the if/elseif and leave only the condition of the elseif.

PS: Http headers like X-Forwarded-For can be spoofed easily, I suggest to stick with REMOTE_ADDR.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement