1
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?

0

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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().

1 Comment

He is calling fopen() to write to the file.
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.