Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Other File Functions

There are three functions that allow you to work more intimately with the contents of a file: rewind(), fseek(), and fwrite(). We already looked at fwrite(), but the other two functions are new. The first, rewind(), is a 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 reread a file or write over whatever you have already written.

The second, 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 the start of the file, meaning that passing 23 will move to the 24th byte 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." For example:

    $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);

Tip

The first byte of a file is byte 0, and you count upward from there—the second byte is at index 1, the third at index 2, etc.

To begin with, the string "Mnnkyys" is written to ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page