Jump to content

Adding up numbers in .txt file


graham23s

Recommended Posts

Hi Guys,

 

What i am thinking of doing is storing unique ip addresses that visit my site in a .txt file on server, only when a new ip address is found i add that to the .txt file, when a new ip is found i assign a random number between 80 and 750 so the .txt file would look something like:

 

xx.xxx.xxx.xxx|567

xx.xxx.xxx.xxx|489

 

i can do that but i'm not sure how to loop and add all the values on the right hand side, any help would be appreciated.

 

thanks guys

 

Graham

 

Link to comment
Share on other sites

Read file. That will return an array. That array has length equal to the number of lines in your text file. Each entry is a line in the file. So you can loop through it and just add the number at the end. :P

 

Does that make sense? Give it a try. It's not as hard as I made it to be. The link to file has great examples already.

Link to comment
Share on other sites

function santas_little_helper2($value) {
    return $value . '|' . mt_rand(80, 750);
}

// converts
// xxx.xxx.xxx.xxx
// xxx.xxx.xxx.xxx
// xxx.xxx.xxx.xxx
// into
// xxx.xxx.xxx.xxx|123
// xxx.xxx.xxx.xxx|456
// xxx.xxx.xxx.xxx|749
file_put_contents('path/to/ip/file.txt', implode(PHP_EOL, array_map('santas_little_helper2', file('path/to/ip/file.txt', FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES));

 

Afterwards read out the ip-addresses with:

 

function santas_little_helper($value) {
    return explode('|', $value);
}

$data = array_map('santas_little_helper', file('path/to/ip/file.txt', FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES));
//$data[0] = array ( [0] => xxx.xxx.xxx.xxx, [1] => 567 )

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.