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
fseek(resource $handle, int $offset, int $whence = SEEK_SET): int
Example
Move the pointer to the 10th byte from the beginning of the file:
<?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
$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
$file = fopen('test.txt', 'r');
fseek($file, -5, SEEK_END);
echo fgets($file);
fclose($file);
?>
Example
Check the result of fseek execution:
<?php
$file = fopen('test.txt', 'r');
$res = fseek($file, 10);
echo $res; // 0 on success, -1 on error
fclose($file);
?>
Code execution result:
0