Other file functions

bool rewind ( resource handle)

int fseek ( resource handle, int offset [, int from_where])

There are three functions that allow you to work more intimately with the contents of a file, which are rewind(), fseek(), and fwrite(). We already looked at fwrite(), but the other two functions are new. Rewind() is a very helpful function that moves the file pointer for a specified file handle (parameter one) back to the beginning. That is, if you call rewind($handle), the file pointer of $handle gets reset to the beginning - this allows you to re-read in a file, or write over whatever you have already written.

Fseek() allows you to move a file handle's pointer to an arbitrary position, specified by parameter two, with parameter one being the file handle to work with. If you do not specify a third parameter, fseek() sets the file pointer to be from the start of the file, meaning that passing 23 will move to byte 24 of the file (files start from byte 0, remember). For the third parameter you can either pass SEEK_SET, the default, which means "from the beginning of the file", SEEK_CUR, which means "relative to the current location", or SEEK_END, which means "from the end of the file".

Here is a simple example of rewind() and fseek() in action:

<?php
    $handle = fopen($filename, "w+");
    fwrite($handle, "Mnnkyys\n");
    rewind($handle);
    fseek($handle, 1);
    fwrite($handle, "o");
    fseek($handle, 2, SEEK_CUR);
    fwrite($handle, "e");
    fclose($handle);
?>

Author's Note: do not forget that the first byte of a file is byte 0, and you count upwards from there - the second byte is at index 1, the third at index 2, etc.

To begin with, the string "Mnnkyys" is written to $handle, which is straightforward enough. However, rewind() is then called to move the file pointer back to the beginning of the file (the letter "M"), then fseek() is called with 1 as the second parameter to move the file pointer to offset 1 in the file, which is currently the first of two letter "n"s. Fwrite() is called again, writing an "o" - this will replace the current letter "n" at that offset with an "o". Fseek() is called again, passing in 2 and SEEK_CUR, which means "move to the byte 2 ahead of the current byte", which happens to be the first of two letter "y"s. Fwrite() is called for the last time, replacing that "y" with an "e", and finally the file is closed - I will leave it to you to figure out its contents!

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Checking whether a file exists >>

Previous chapter: Temporary files

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.