PHP fseek() Function
The PHP fseek() function sets the file position indicator for specified file stream. The new position is measured in bytes from the beginning of the file and is obtained by adding offset to the position specified by whence parameter.
In general, it is allowed to seek past the end-of-file. If data is then written, reads in any unwritten region between the end-of-file and the sought position will yield bytes with value 0. However, certain streams may not support this behavior, especially when they have an underlying fixed size storage.
Syntax
fseek(stream, offset, whence)
Parameters
stream |
Required. Specify the file pointer to seek in. It must be valid, and must point to a file successfully typically opened by using fopen() function. |
offset |
Required. Specify the new position (measured in bytes from the beginning of the file) |
whence |
Optional. Default is SEEK_SET. Possible values are:
|
Return Value
Returns 0 on success, otherwise returns -1.
Example:
Lets assume that we have a file called test.txt. This file contains following content:
This is a test file. It contains dummy content.
The example below describes the use this function while reading a file.
<?php //open the file in read mode $fp = fopen("test.txt", "r") or die("Unable to open file!"); //reading the first line from the file echo "1. ".fgets($fp, 4096); //setting the file pointer to the start of //file and reading the first line again fseek($fp, 0); echo "2. ".fgets($fp, 4096); //setting the file pointer to the 5 bytes from the //start of file and reading the first line again fseek($fp, 5); echo "3. ".fgets($fp, 4096); //setting the file pointer past the current //position by 12 bytes and reading the line fseek($fp, 12, SEEK_CUR); echo "4. ".fgets($fp, 4096); //close the file fclose($fp); ?>
The output of the above code will be:
1. This is a test file. 2. This is a test file. 3. is a test file. 4. dummy content.
❮ PHP Filesystem Reference