保存时间戳和IP地址

时间:2019-06-10 00:13:27

标签: php html

当用户访问时,我会将IP地址和他们访问的时间保存到一个文本文件中(此文件受保护且不可公开访问)。

PHP是:

 <?php
$file = "ipaddresses.txt";
$timestamp =date('l jS \of F Y h:i:s A');
$f=fopen($file, 'a+');
fwrite($f,$_SERVER['REMOTE_ADDR'], $timestamp."\n");
fclose($f);
?>

我认为我只是将第二个timestamp标记放置在错误的位置,但是即使我节省了其他表格的时间,也似乎无法使用REMOTE ADDR来解决它,只是发布了所有一次输入。

似乎很简单,但我迷路了,因此不胜感激。

EDIT 1:

请查看更新的代码;

<?php
$file = "ipaddresses.txt";
$timestamp =date('l jS \of F Y h:i:s A');
$f=fopen($file, 'a+');
$info = $_SERVER['REMOTE_ADDR'] . $timestamp . "\n";
fwrite($f, $info);
fclose($f);
?>

3 个答案:

答案 0 :(得分:1)

fwrite() 仅接受两个参数;文件和要写入的信息。

这样,您可能希望将IP和时间戳连接为一个字符串:

fwrite($f, $_SERVER['REMOTE_ADDR'] . $timestamp . "\n");

或者:

$info = $_SERVER['REMOTE_ADDR'] . $timestamp . "\n";
fwrite($f, $info);

答案 1 :(得分:1)

<?php
$file = "ipaddresses.txt";
$timestamp =date('l jS \of F Y h:i:s A');
$f=fopen($file, 'a+');
$info = $_SERVER['REMOTE_ADDR'] . $timestamp . "\n";
fwrite($f, $info);
fclose($f);
?>

答案 2 :(得分:0)

function getRealIpAddr(){
    if(isset($_SERVER["HTTP_CF_CONNECTING_IP"])){
        $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
        $_SERVER['HTTP_CLIENT_IP'] = $_SERVER["HTTP_CF_CONNECTING_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;
    }
    return $ip;
}

$Ip_Address = getRealIpAddr();
$Timestamp = date("Y-m-d H:i:s");
$array = array("IP"=>$Ip_Address,"Timestamp"=>$Timestamp);
$myfile = fopen("ipaddresses.txt", "a+") or die("Unable to open file!");
fwrite($myfile, json_encode($array));
fclose($myfile);