In PHP, fseek() moves the file pointer of an open file to a new position. The pointer is the invisible marker that tells PHP where the next read or write will happen.
You pass the open file handle, the number of bytes to move, and where to count from. It returns 0 when the move works and -1 when it fails, which is the opposite of what many beginners expect.
Syntax
Call fseek() with the values you need. Start with this line.
PHP
$result = fseek($fp, 6);
Call
What it does
fseek($fp, 6)
Moves the pointer to byte 6 counted from the start of the file.
fseek($fp, -3, SEEK_END)
Moves the pointer to 3 bytes before the end of the file.
fseek($fp, 2, SEEK_CUR)
Moves the pointer 2 bytes forward from where it is now.
fseek() returns 0 on success and -1 on failure. Do not write if (fseek(...)) to test for success, because 0 counts as false in PHP. Compare with === 0 instead.
Library declarations
PHP
fseek(resource $stream, int $offset, int $whence = SEEK_SET): int
Parameters
Parameter
Description
stream
Required. A file handle returned by fopen(). The file must still be open.
offset
Required. The number of bytes to move. It can be negative when you use SEEK_CUR or SEEK_END.
whence
Optional. Where to count from: SEEK_SET (start of file, the default), SEEK_CUR (current position) or SEEK_END (end of file).
Return Value
Return Value
Description
int
Returns 0 on success and -1 on failure. Seeking past the end of a file is allowed and still returns 0.
PHP Examples
Example 1 — Jump to a Position and Read
Write a short text file, then skip the first 6 bytes and read the rest.