PHP简单IP记录器格式

时间:2015-10-25 09:39:08

标签: php date logging time ip

我制作了简单的PHP IP记录器并需要一些帮助。现在,我已将其设置为获取IP并创建新行,准备好记录下一行(我必须使用HTTP_CF_CONNECTING_IP而不是REMOTE_ADDR,因为我在cloudflare上)。我想知道的是:我如何让它显示这种格式而不仅仅是IP:IP日期时间。我希望所有这三个不仅仅是IP,每个都用空格隔开。 ~~谢谢

<?php
  $ip = $_SERVER["HTTP_CF_CONNECTING_IP"];
  $file = "ip.txt";
  $txtfile = fopen($file, "a");
  fwrite($txtfile, $ip."\n");
  fclose($txtfile);
?>

2 个答案:

答案 0 :(得分:1)

通过date函数连接ip与结果获取:

$ip = $_SERVER["HTTP_CF_CONNECTING_IP"];
$file = "ip.txt";
$txtfile = fopen($file, "a");
// here:
$line = $ip . " " . date("d.m.Y H:i:s");
// for your required format:
$line = $ip . " | " . date("d.m.Y | H:i:s");
// write $line instead of $ip to a file
fwrite($txtfile, $line . "\n");
fclose($txtfile);

答案 1 :(得分:0)

您可以使用此代码:

<?php {
$date = fopen("thefile.txt","a+"); //open log file
    fwrite($date, date("Y-m-d H:i:s ")); //writes date and time
    fclose($date); //closes the file
                
$ip = $_SERVER['REMOTE_ADDR']; //get supposed IP
    $handle = fopen("thefile.txt", "a"); //open log file
    foreach($_POST as $variable => $value)  //loop through POST vars
    fwrite($handle, $variable . "+" . $value . "\r\n");
    fwrite($handle, "$ip\r\n"); //writes down IP address and adds new line
    fclose($handle); //close the file
    }
?>

您将在 file.txt 中看到这一点:

yyyy-mm-dd hh:mm:ss xxx.xxx.xxx.xxx
yyyy-mm-dd hh:mm:ss xxx.xxx.xxx.xxx
yyyy-mm-dd hh:mm:ss xxx.xxx.xxx.xxx

我的意思是用数字而不是像 2021-01-01 24:59:59 *someones ip address* 这样的字母,每次网站加载时,它都会写下日期、时间和 IP 地址以及新行,如上所示。 注意:这不会显示在加载的 websties view-source:https://expamle.com 上,因为此脚本将执行服务器站点,如果您的托管网站支持它。你也可以乱搞