PHP Reference ยท Files and I/O
PHP feof(), fseek() and ftell() functions
Reference for PHP feof(), fseek(), ftell() and rewind(): move around a file handle, read the current position, detect end of file and avoid the feof loop trap.
Every open file handle has a position: the byte where the next read or write happens. ftell() tells you the position, fseek() moves it, rewind() jumps back to the start, and feof() reports whether a read has reached the end of the file.
Together they let you re-read data, jump to a known offset (for example a fixed-size record) or overwrite part of a file. They work on seekable streams such as regular files and php://memory, not on pipes or sockets.
fseek($handle, 10); // move to byte 10 echo ftell($handle); // 10 rewind($handle); // back to byte 0
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
feof(resource $stream): bool fseek(resource $stream, int $offset, int $whence = SEEK_SET): int ftell(resource $stream): int|false rewind(resource $stream): bool
| Name | Description |
|---|---|
$stream |
An open, seekable file handle. |
$offset |
Number of bytes to move. May be negative with SEEK_CUR and SEEK_END. |
$whence |
SEEK_SET (from the start, default), SEEK_CUR (from the current position) or SEEK_END (from the end). |
Return value: feof() returns true once a read hit the end. fseek() returns 0 on success and -1 on failure. ftell() returns the position or false. rewind() returns true on success.
Usage notes
feof()lags behind. It becomes true only after a read attempt touched the end, sowhile (!feof($h))runs one extra time andfgets()returnsfalseon that last pass. Loop onfgets() !== falseinstead.- Seeking past the end is allowed for files. The next write fills the gap with null bytes; reading returns nothing.
- A negative absolute position fails:
fseek($h, -1)returns-1and the position stays unchanged. - Append mode (
"a") ignores seeks for writes: data always goes at the end. - Writing overwrites bytes at the current position; it does not insert.
- Not seekable: pipes,
php://stdinfrom a terminal and network sockets.fseek()returns-1there. - Positions count bytes, not characters, so they can fall in the middle of a UTF-8 sequence.
ftell()and buffers. In append mode its result may not reflect where the next write lands.