Master PHP File Positioning with fseek(): Syntax, Options, and Examples

Learn how to use PHP's fseek() function to move file pointers, understand its parameters—including offset and whence options like SEEK_SET, SEEK_CUR, and SEEK_END—and see a complete example that demonstrates reading, writing, and repositioning within a file.

php Courses
php Courses
php Courses
Master PHP File Positioning with fseek(): Syntax, Options, and Examples

In PHP file operations, you often need to position the file pointer at a specific location. PHP provides the useful function fseek() for this purpose.

The fseek() function moves the file pointer to a specified position, allowing reading, writing, or appending data.

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 stays.

whence : optional. Determines how the offset is applied. Possible values:

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 first 10 bytes
    echo fread($file, 10);

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

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

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

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

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

The script opens a file with fopen() in read‑write mode, uses fseek() to reposition the pointer, reads and writes data with fread() and fwrite(), and finally closes the file.

Overall, fseek() is a flexible function that enables locating any position within a file, facilitating operations such as adding, deleting, or modifying data efficiently.

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.

PHPfile-handlingfile-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.