How to Use fseek in PHP to Move File Pointer

In PHP, navigating through a file efficiently is crucial when you need to read or write data at specific locations. This article provides a quick, straight-to-the-point guide on how to use the fseek() function to move the file pointer to a specific byte position, explaining its syntax, parameter options, and providing a practical code example.

The fseek() function is used to position the file pointer of an open file. To use it, you must first open the file using fopen(), which returns a file pointer resource.

Syntax of fseek()

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

The function returns 0 on success, and -1 on failure.

Practical Example

The following example demonstrates how to open a file, move the pointer to the 10th byte, and read data from that position.

<?php
// Open the file in read-only mode
$file = fopen("example.txt", "r");

if ($file) {
    // Move the file pointer to the 10th byte from the beginning
    $status = fseek($file, 10, SEEK_SET);

    if ($status === 0) {
        // Read 20 bytes starting from the new pointer position
        $data = fread($file, 20);
        echo "Data read from byte 10: " . $data;
    } else {
        echo "Failed to move the file pointer.";
    }

    // Always close the file handle
    fclose($file);
} else {
    echo "Could not open the file.";
}
?>

Key Considerations