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

Learn how PHP’s fseek() function lets you position the file pointer anywhere in a file, understand its syntax, parameters like offset and whence, and see a complete example that demonstrates opening, seeking, reading, writing, and closing a file.

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

function moves the file pointer to a specified location, enabling reading, writing, or appending at different positions in an opened file.

Syntax of fseek()

fseek(file, offset, whence)
file

: required, the file resource opened with fopen(). offset: required, number of bytes to move the pointer; positive moves forward, negative moves backward, zero keeps the current position. 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 beginning
    fseek($file, 0, SEEK_SET);

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

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

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

    // Move pointer back to the beginning
    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 whole file before closing it.

Overall, fseek() is a flexible and essential function for precise file manipulation 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-pointerfseek
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.