Mastering PHP’s fseek(): How to Move File Pointers Efficiently

This article explains PHP’s fseek() function, detailing its syntax, parameters, and usage examples for positioning file pointers, reading, writing, and appending data, and demonstrates practical code snippets that illustrate flexible file manipulation techniques.

php Courses
php Courses
php Courses
Mastering PHP’s fseek(): How to Move File Pointers Efficiently
fseek()

moves the file pointer to a specified location, enabling reading, writing, or appending at arbitrary positions within an opened file.

Syntax of fseek()

fseek(file, offset, whence)
file

: required; the file resource opened by fopen(). offset: required; the number of bytes to move the pointer. Positive values move forward, negative values move backward, zero leaves the pointer unchanged. whence: optional; determines how the offset is interpreted. Possible values are: SEEK_SET (default): set pointer to the beginning of the file. SEEK_CUR: set pointer relative to the current position. SEEK_END: set pointer relative to the end of the file.

Example usage of fseek()

<?php
$file = fopen("example.txt", "r+");
if ($file) {
    // Move pointer to the start of the file
    fseek($file, 0, SEEK_SET);

    // Read and output the first 10 bytes
    echo fread($file, 10);

    // Move pointer to the end of the file
    fseek($file, 0, SEEK_END);

    // Write a new line to the file
    fwrite($file, "This is a new line.");

    // Move pointer back to the start
    fseek($file, 0, SEEK_SET);

    // Read and output the entire file
    echo fread($file, filesize("example.txt"));

    // Close the file
    fclose($file);
}
?>

The script opens a file in read‑write mode, uses fseek() to position the pointer at the start, reads the first 10 bytes, moves to the end to append a new line, then returns to the start to read the full contents before closing the file.

Through this example, it is clear that fseek() is a flexible and essential function for precise file handling in PHP, allowing developers to add, delete, or modify data at any location within a file.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backend DevelopmentPHPfile I/Ofile-handlingfseek
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.