15 – PHP File Handling: Moving the File Pointer


If you have remembered in one of our lesson the writing of the file, we talked about the idea of the file pointer or its like a cursor in a word processor. So in file handling we have the ability to move the pointer around the file to write in different places within the file. And this will be our focus for this lesson.

To start in this lesson lets create a new PHP file and lets call it as “filepointer.php” and add the following code.


//specify the filename and we call it as hello.txt

$testfile = ‘hello.txt’;

//and inside the if statement, we pass the $testfile variable to fopen and we specify the mode as write

//and fopen return a handle as a value, and using handle is useful because we could close it

if($fh = fopen($testfile, ‘w’)){// we are overwriting

//returns number of bytes or false

$greetings = “abc\r\ndef\r\nghi”;

fwrite($fh, $greetings);

//this will return the position of our pointer or cursor and we can use it as key for moving around

$position = ftell($fh);

//used to seek new location for us, and we’re going tell what position is going to go to

//and it moves back five position

fseek($fh, $position -5);

fwrite($fh, “rst”);

//to go back at the beginning of the file


fwrite($fh, “xyz”);

//close the handle






Facebook Comments


Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.