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$handle: The file system pointer resource returned byfopen().$offset: The byte offset. This value can be positive to move forward or negative to move backward.$whence: Optional. This parameter defines how the offset is interpreted. It accepts three constants:SEEK_SET(Default): Sets the position equal to$offsetbytes from the beginning of the file.SEEK_CUR: Sets the position to the current location plus$offset.SEEK_END: Sets the position to the end-of-file plus$offset(use a negative offset to move backward from the end).
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
- Write Mode Behavior: If you open a file in append
mode (
"a"or"a+"), any data you write will always be appended to the end of the file, regardless of any pointer movement usingfseek(). - Pointer Exceeding File Size: You can seek past the
end-of-file. If you do this and then write data, the gap between the
original end of the file and the new data will be filled with null bytes
(
\0).