The fseek Function

The fseek function allows moving the position pointer in a file. Its first parameter is a file pointer, the second is an offset in bytes, and the third (optional) is the reference point. The function returns 0 on success and -1 on error.

Syntax

phpfseek(resource $handle, int $offset, int $whence = SEEK_SET): int

Example

Move the pointer to the 10th byte from the beginning of the file:

php<?php
  $file = fopen('test.txt', 'r');
  fseek($file, 10);
  echo fgets($file);
  fclose($file);
?>

Example

Move the pointer 5 bytes from the current position:

php<?php
  $file = fopen('test.txt', 'r');
  fseek($file, 5, SEEK_CUR);
  echo fgets($file);
  fclose($file);
?>

Example

Move the pointer 5 bytes from the end of the file:

php<?php
  $file = fopen('test.txt', 'r');
  fseek($file, -5, SEEK_END);
  echo fgets($file);
  fclose($file);
?>

Example

Check the result of fseek execution:

php<?php
  $file = fopen('test.txt', 'r');
  $res = fseek($file, 10);
  echo $res; // 0 on success, -1 on error
  fclose($file);
?>

Code execution result:

php0

See Also

  • the rewind function,
    which resets the file pointer
  • the ftell function,
    which returns the current position
  • the fread function,
    which reads from a file