Free Source Code and Tutorials

Custom Search

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
(Visited 8 times, 1 visits today)
Share this

Check Your Domain Ranking

Leave a Reply

Your email address will not be published. Required fields are marked * © 2016 Frontier Theme

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!

%d bloggers like this: