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.
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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
