Open In App

PHP | fseek( ) Function

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.

Return Value: It returns 0 on success, or -1 on failure.



Exceptions:

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


Article Tags :