Search code examples
phpsplsplfileobject

PHP LimitIterator fails ("Does not support seeking" + "Cannot rewind file")


I use SplFileObject and LimitIterator to read content from position x till y of a big file.

This works perfectly when using a file path like /home/devel/stuff/myfile.log.

When using a path like http://mydomain.com:8090/devel/stuff/myfile.log it does not work. The path is correct however.

Does this fail when using absolute paths?


The error messages are:

PHP Warning: SplFileObject::rewind() [<a href='splfileobject.rewind'>splfileobject.rewind</a>]: stream does not support seeking in ...

PHP Fatal error: Uncaught exception 'RuntimeException' with message 'Cannot rewind file ...'


Full code:

  // $pStrFile contains the valid (yes!) path
  $oFile = new SplFileObject($pStrFile);
  // $nFrom = 80 and $nLines = 30
  $fileIterator = new LimitIterator($oFile, $nFrom, $nLines);

  foreach($fileIterator as $line) {
      $strLines .= $line;
  }

Solution

  • This is a limitation of the http wrapper. If a file is on the disk, you can access it on any position. If you want to start reading in the middle of the file, that is possible. However, when the file is on a webserver and you get it with HTTP, it is a little bit harder to read the middle of the file.

    You can copy the file to a temporary location and then use the LimitIterator on it.