1

ユーザーが私の Web サイトでアカウントにサインアップすると、USERNAME.php という独自のページが作成されます。
ユーザー名「bob」がサインインするたびに、新しい行が bob.php に追加されます。これには、そのログインの時刻、日付、および IP アドレスが含まれます。

私がやりたいことは、ファイルが時間の経過とともに大きくなりすぎないように、そのファイルに最大 20 行を含めることです。
最初の行は "Login Retrieval for bob " で、最後に最新のログイン結果が表示されます。そのため、最初の行は削除すべきではありませんが、2 行目はログインのたびに削除する必要があります (行数が 20 を超える場合のみ)。これを行うための最良の方法は何ですか?ありがとう!

4

2 に答える 2

0

.php拡張子は使用せず、ファイルは最大 20 行であると想定しています。

file()関数を使用してファイルを行単位で展開shiftし、最初の行を取り出して保存し、 を使用array_splice()して最後の 19 行を抽出しunshift、最初の行を新しい配列に戻して、最大 20 のエントリを取得できます。joinそれらを元のファイルに書き直します。

さらに良いことに、それらを新しいファイルに書き込み、すべてがうまくいった場合は、新しいファイルの名前を新しいファイルに変更します。

    /**
     * @param $file    the input file
     * @param $n       total number of meaningful lines to keep (default 20)
     * @param $m       prefix lines to keep (default 1)
     *
     * @return         number of lines in case something was done
     *                 0 nothing to do
     *                 -1 file not found
     *                 -2 file not readable
     *                 -3 file not writeable
     *                 -4 write error
     *                 -8 bad parameter
     */

    function trim_file($file, $n = 20, $m = 1)
    {
            if (!file_exists($file))
                    return -1;
            if (!is_readable($file))
                    return -2;
            if (!is_writeable($file))
                    return -3;
            if ($m > $n)
                    return -8;
            $lines  = file($file);
            $num    = count($lines);

            // If file is short, no need to do anything
            if ($num <= $n)
                    return 0;

            $header = array_slice($lines, 0, $m);
            // Remove lines from 0 to ($num-($n-$m))
            // and replace them with the first $m lines
            array_splice($lines, 0, $num-($n-$m), $header);

            // Write file with new contents
            $fp = fopen($file . '.tmp', 'w');
            if (!$fp)
                    return -4;
            fwrite($fp, join('', $lines));
            fclose($fp);

            // Replace the file in one fell swoop.
            rename($file . '.tmp', $file);
            return count($lines);
    }
于 2013-04-02T21:00:46.577 に答える