Menu Home

fseek

osbo.com | PHP | Functions | fseek

Seeks on a file pointer

Syntax

fseek ( resource $handle , int $offset [, int $whence = SEEK_SET ] ) : int

Parameters

handle

A file system pointer resource that is typically created using fopen().

offset

The offset. To move to a position before the end-of-file, you need to pass a negative value in offset and set whence to SEEK_END.

whence
SEEK_SET Set position equal to offset bytes.
SEEK_CUR Set position to current location plus offset.
SEEK_END Set position to end-of-file plus offset.

Return

Upon success, returns 0; otherwise, returns -1.

Examples

handle offset = 0

<?

$filename = $_SERVER['DOCUMENT_ROOT'] . '/assets/txt/file.txt';
$mode = 'r';

$handle = fopen($filename, $mode);

    // read some data
    $data = fgets($handle, 4096);
    echo $data . PHP_EOL;

    // move to the beginning of the file - same as rewind($handle)
    $offset = 0;
    fseek($handle, $offset);

    // read some data
    $data = fgets($handle, 4096);
    echo $data;

fclose($handle);

?>
Hello
Hello

handle offset = 2

<?

$filename = $_SERVER['DOCUMENT_ROOT'] . '/assets/txt/file.txt';
$mode = 'r';

$handle = fopen($filename, $mode);

    // read some data
    $data = fgets($handle, 4096);
    echo $data . PHP_EOL;

    // move to the beginning of the file with an offset of 2
    $offset = 2;
    fseek($handle, $offset);

    // read some data
    $data = fgets($handle, 4096);
    echo $data;

fclose($handle);

?>
Hello
llo

whence | SEEK_SET

<?

$filename = $_SERVER['DOCUMENT_ROOT'] . '/assets/txt/file.txt';
$mode = 'r';

$handle = fopen($filename, $mode);

    // read some data
    $data = fgets($handle, 4096);
    echo $data . PHP_EOL;

    // move to the beginning of the file with an offset of 2
    $offset = 2;
    $whence = SEEK_SET;
    fseek($handle, $offset, $whence);

    // read some data
    $data = fgets($handle, 4096);
    echo $data;

fclose($handle);

?>
Hello
llo

whence | SEEK_CUR

<?

$filename = $_SERVER['DOCUMENT_ROOT'] . '/assets/txt/file.txt';
$mode = 'r';

$handle = fopen($filename, $mode);

    // read some data
    $data = fgets($handle, 3);
    echo $data . PHP_EOL;

    // move to the current location with an offset of 2
    $offset = 2;
    $whence = SEEK_CUR;
    fseek($handle, $offset, $whence);

    // read some data
    $data = fgets($handle, 4096);
    echo $data;

fclose($handle);

?>
He
o

whence | SEEK_END

<?

$filename = $_SERVER['DOCUMENT_ROOT'] . '/assets/txt/file.txt';
$mode = 'r';

$handle = fopen($filename, $mode);

    // read some data
    $data = fgets($handle, 4096);
    echo $data . PHP_EOL;

    // move to the end of the file with an offset of 2
    $offset = -2;
    $whence = SEEK_END;
    fseek($handle, $offset, $whence);

    // read some data
    $data = fgets($handle, 4096);
    echo $data;

fclose($handle);

?>
Hello
lo

PHP