PHP Tutorial - PHP fseek() Function


The fseek() function seeks in an open file, by moving the file pointer from its current position to a new position, forward or backward, specified by the number of bytes.


PHP fseek() Function has the following syntax.



ParameterIs RequiredDescription
fileRequired.Open file to seek in
offsetRequired.New position (measured in bytes from the beginning of the file)

Possible values for whence:

  • SEEK_SET - Set position equal to offset. Default
  • SEEK_CUR - Set position to current location plus offset
  • SEEK_END - Set position to EOF plus offset to move to a position before EOF, the offset must be a negative value


This function returns 0 on success, or -1 on failure. Seeking past EOF will not generate an error.


fseek() moves a file handle pointer to an arbitrary position.

<?PHP// ww  w.  j av  a2s . c  o  m
      $filename = "c:/abc/test.txt";
      $handle = fopen($filename, "w+");
      fwrite($handle, "\n");
      fseek($handle, 1);
      fwrite($handle, "o");
      fseek($handle, 2, SEEK_CUR);
      fwrite($handle, "e");

The first byte of a file is byte 0, and you count upward from there. The second byte is at index 1, the third at index 2, etc.

Find the current position by using ftell().