The fseek() function in PHP is an inbuilt function which is used to seek in an open file. It moves the file pointer from its current position to a new position, forward or backward specified by the number of bytes. The file and the offset are sent as parameters to the fseek() function and it returns 0 on success, or -1 on failure.
Syntax:
int fseek ( $file, $offset, $whence)
Parameters: The fseek() function in PHP accepts three parameters as described below.
- $file: It is a mandatory parameter which specifies the file.
- $offset: It is a mandatory parameter which specifies the new position of the pointer. It is measured in bytes from the beginning of the file.
-
$whence: It is an optional parameter which can have the following possible values-
- SEEK_SET: It sets position equal to offset.
- SEEK_CUR: It sets position to current location plus offset.
- SEEK_END: It sets position to EOF plus offset. To move to a position before EOF, the offset must be a negative value.
Return Value: It returns 0 on success, or -1 on failure.
Exceptions:
- Seeking past EOF(end of file) generates an error.
- If a file is open in append (a or a+) mode, then any data written to the file will always be appended, regardless of the file position, and the result of calling fseek() will be undefined.
- Not all streams support seeking. For those that do not support seeking, forward seeking from the current position is accomplished by reading and discarding data; other forms of seeking will fail.
Below programs illustrate the fseek() function in PHP:
Program 1: In the below program the file named gfg.txt contains the following content:
Geeksforgeeks is a portal for geeks!
<?php // Opening a file $myfile = fopen ( "gfg.txt" , "w" );
// reading first line fgets ( $myfile );
// moving back to the beginning of the file echo fseek ( $myfile , 0);
// closing the file fclose( $myfile );
?> |
Output:
0
Program 2: In the below program the file named gfg.txt contains the following content:
Geeksforgeeks is a portal for geeks!
<?php // Opening a file $myfile = fopen ( "gfg.txt" , "w" );
// reading first line fgets ( $myfile );
// fseek() pointing to the end of the file fseek (fp, 0, SEEK_END);
// closing the file fclose( $myfile );
?> |
Output:
36
Reference: http://php.net/manual/en/function.fseek.php