开发者

Why function file returns empty array?

Done
<?php
    define('FILE_NAME', 'list.dat');
    define('MAX_BREAK', 30);

    function write($file, $ip, $time)
    {
        fwrite($file, $ip . '|' . $time . "\n");
    }

    $new_ip = /*$REMOTE_ADDR*/ $_SERVER['REMOTE_ADDR'];
    $file = fopen(FILE_NAME, 'w+');
    flock($file, LOCK_EX | LOCK_SH);

    $array = file(FILE_NAME, FILE_IGNORE_NEW_LINES);
    $contains = false;
    foreach ($array as $record)
    {
开发者_运维技巧        $values = explode('|', $record);
        $ip = $values[0];
        $time = $values[1];
        if ($ip == $new_ip)
        {
            $time = time();
            $contains = true;
        }
        if (time() - $time < MAX_BREAK)
            write($file, $ip, $time);
    }
    if (!$contains)
        write($file, $new_ip, time());

    flock($file, LOCK_UN);
    fclose($file);
?>

$array is empty, but it shouldn't because file contains one line. Any ideas why?


Because list.dat is empty.

fopen with w+

'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.


If the file command is returning false, it means file() failed. I think it might be failing because you already have it locked with your flock() call. The file() function does not need to be preceded by an fopen().


Using flock() you aquire an exclusive lock on the file and after that you want to read it. That doesn't work. A shared lock will probably be enough (no one can alter the file while it's locked).

flock($file, LOCK_EX | LOCK_SH);

becomes

flock($file, LOCK_SH);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜