【问题标题】:How to redirect echo to txt in php?如何在php中将echo重定向到txt?
【发布时间】:2021-09-11 13:01:02
【问题描述】:

您好,我正在尝试将访问我网站的 IP 地址写入日志文件。这是我的代码:

function getRealIpAddr(){
 if ( !empty($_SERVER['HTTP_CLIENT_IP']) ) {
  // Check IP from internet.
  $ip = $_SERVER['HTTP_CLIENT_IP'];
 } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
  // Check IP is passed from proxy.
  $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
 } else {
  // Get IP address from remote address.
  $ip = $_SERVER['REMOTE_ADDR'];
 }
 return $ip;
}

echo getRealIpAddr();

我想获得“echo getRealIpAddr();”到我创建的“iplogs.txt”

【问题讨论】:

    标签: php ip


    【解决方案1】:

    使用file_put_contents($filename, $data, FILE_APPEND)FILE_APPEND 不会覆盖之前的数据。

    阅读file_put_contents

    所以在你的情况下,代码是

    $ip = getRealIpAddr();
    $filename = '/full/path/to/iplogs.txt';
    file_put_contents($filename, $ip, FILE_APPEND)
    

    您可以像这样使用\r\nPHP_EOL 添加换行符

    file_put_contents($filename, $ip . PHP_EOL, FILE_APPEND)
    

    【讨论】:

    • 谢谢,它有效,我已经将 PHP_EOL 添加到 $ip,它在第一行给出了最后一个 IP。
    • FILE_APPEND 应该将内容添加到文件的末尾。检查文档中的示例 #2
    • 对不起,我的错误,我有一个仔细检查,它在最后。不过,这是一个好的开始。
    【解决方案2】:

    使用php函数file_put_contents

    https://www.php.net/manual/en/function.file-put-contents.php

    <?php
    $file = 'iplogs.txt';
    // Open the file to get existing content
    $current = file_get_contents($file);
    // Append a new output to the file
    $current .= getRealIpAddr();
    // Write the contents back to the file
    file_put_contents($file, $current);
    ?>
    

    【讨论】:

    • 视文件大小而定;在写入之前读取整个文件将是一个糟糕的资源密集型想法。
    猜你喜欢
    • 1970-01-01
    • 2012-02-26
    • 2017-05-25
    • 2011-05-05
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 2011-03-20
    相关资源
    最近更新 更多