Question

Why is my PHP script hanging?

$path = tempnam(sys_get_temp_dir(), '').'.txt';
$fileInfo = new \SplFileInfo($path);
$fileObject = $fileInfo->openFile('a');
$fileObject->fwrite("test line\n");
var_dump(file_exists($path));          // bool(true)
var_dump(file_get_contents($path));    // string(10) "test line
                                       // "
var_dump(iterator_count($fileObject)); // Hangs on this

If I delete the last line (iterator_count(...) and replace it with this:

$i = 0;
$fileObject->rewind();
while (!$fileObject->eof()) {
    var_dump($fileObject->eof());
    var_dump($i++);
    $fileObject->next();
}
// Output:
// bool(false)
// int(0)
// bool(false)
// int(1)
// bool(false)
// int(2)
// bool(false)
// int(3)
// bool(false)
// int(4)
// ...

The $fileObject->eof() always returns false so I get an infinite loop.

Why are these things happening? I need to get a line count.

Was it helpful?

Solution

By what I see in your code, you are opening the file with mode a at this line:

$fileObject = $fileInfo->openFile('a');

When you do that, its write only:

$fileObject->eof() needs to read the file, you should open the file with a+ to allow read/write:

$fileObject = $fileInfo->openFile('a+');

Ps: either with a or a+, the pointer goes to the end of the file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top